package com.cloudkinto.service.orderinput.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.*;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.extentity.shelf.StoragePreviewDto;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.dic.vo.LanguageValueEntity;
import com.cloudkinto.service.email.MailSenderService;
import com.cloudkinto.service.fbaorderoutput.FbaOrderOutputService;
import com.cloudkinto.service.fbaorderoutput.vo.FbaOrderOutputPackageUpdateReq;
import com.cloudkinto.service.fbaorderoutput.vo.FbaOrderOutputProductDetail;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.finance.CostRecordService;
import com.cloudkinto.service.headercontainer.HeaderPriceItemService;
import com.cloudkinto.service.headercontainer.vo.HeaderContainerProjectRes;
import com.cloudkinto.service.headercontainer.vo.HeaderFeeSetRequest;
import com.cloudkinto.service.headercontainer.vo.HeaderPriceItemPartExportVo;
import com.cloudkinto.service.headercontainer.vo.OrderHeaderContainerExportVo;
import com.cloudkinto.service.message.MessageNoticeService;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.operate.vo.OperateRes;
import com.cloudkinto.service.orderinput.OrderInputService;
import com.cloudkinto.service.orderinput.vo.*;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.product.ProductOutService;
import com.cloudkinto.service.product.ProductStockFlowingService;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.stock.StockLogService;
import com.cloudkinto.service.storage.StorageService;
import com.cloudkinto.service.user.WxUserService;
import com.cloudkinto.utils.BarCodePdfUtils;
import com.cloudkinto.utils.PdfUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-08
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class OrderInputServiceImpl extends ServiceImpl<OrderInputDao, OrderInputDo> implements OrderInputService {
    @Autowired
    private OrderInputDao dao;
    @Autowired
    private StorageService storageService;
    @Autowired
    private FileService fileService;
    @Autowired
    private OrderInputPackageDao orderInputPackageDao;
    @Autowired
    private OrderInputProductDao orderInputProductDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private ShopService shopService;
    @Autowired
    private OperateRecordService operateRecordDao;
    @Autowired
    private StockRecordDao stockRecordDao;
    @Autowired
    private OrderOutputDao orderOutputDao;
    @Autowired
    private FbaStorageDao fbaStorageDao;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private ThreadPoolTaskExecutor executor;
    @Autowired
    private CostRecordService costRecordService;
    @Autowired
    private CostRecordDao costRecordDao;

    //真正的存储路径
//    @Value("${gbc.uploadPath.filePath}")
//    private String filePath;
    @Autowired
    private StockLogService stockLogService;
    @Autowired
    private CostRecordService costService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private HeaderPriceItemService headerPriceItemService;
    @Autowired
    private StorageServiceProjectDao storageServiceDao;
    @Autowired
    private ExchangeRateDao rateDao;
    @Value("${gbc.template.filePath}")
    private String filePath;
    @Autowired
    private ProductStockDao productStockDao;
    @Autowired
    private ProductOutService productOutService;
    @Autowired
    private HeaderContainerDao headerContainerDao;
    @Autowired
    private ManageBillDao manageBillDao;
    @Autowired
    private HeaderContainerOrderDao headerContainerOrderDao;
    @Autowired
    private ManageHeaderPriceItemDao manageHeaderPriceItemDao;
    @Autowired
    private ManageHeaderRateDao manageHeaderRateDao;
    @Autowired
    private ProductStockRackDao productStockRackDao;
    @Autowired
    private StoragePositionDao storagePositionDao;
    @Autowired
    private ProductStockFlowingService productStockFlowingService;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;
    @Autowired
    private CountryCodeDao countryDao;
    @Autowired
    private MessageNoticeService messageNoticeService;


    @Override
    public SingleResult addInit(Long userId, Long companyId) {
        Map<String, List> listMap = new HashMap<>();
        List<Map> storageList = new ArrayList<>();
        List<StorageDo> storageDos = storageService.getBaseMapper().selectList(null);
        if (!CollectionUtils.isEmpty(storageDos)) {
            for (StorageDo storageDo : storageDos) {
                Map map = new HashMap();
                map.put("id", storageDo.getId());
                map.put("value", storageDo.getStorageName());
                storageList.add(map);
            }
        }
        listMap.put("storage", storageList);
        listMap.put("companyTree", companyService.tree());

        //运输方式
        List<Map> transportTypeList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.transportType);
        List<DicBusinessItemDo> transportType = dicBusinessItemDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(transportType)) {
            transportType.forEach(e -> {
                Map map = new HashMap();
                map.put("id", e.getId());
                map.put("value", e.getDicItemValue());
                transportTypeList.add(map);
            });
        }
        listMap.put("transportTypeList", transportTypeList);

        //发货方式
        List<Map> sendOutTypeList = new ArrayList<>();
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.sendOutType);
        List<DicBusinessItemDo> sendOutType = dicBusinessItemDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(sendOutType)) {
            sendOutType.forEach(e -> {
                Map map = new HashMap();
                map.put("id", e.getId());
                map.put("value", e.getDicItemValue());
                sendOutTypeList.add(map);
            });
        }
        listMap.put("sendOutTypeList", sendOutTypeList);
        List<Map> fbaStorageList = new ArrayList<>();
        List<FbaStorageDo> fbaStorageDoList = fbaStorageDao.selectList(null);
        fbaStorageDoList.forEach(fbaStorageDo -> {
            Map map = new HashMap();
            map.put("id", fbaStorageDo.getId());
            map.put("value", fbaStorageDo.getFbaCode());
            fbaStorageList.add(map);
        });
        listMap.put("fbaStorageList", fbaStorageList);
        listMap.put("sendOutTypeList", sendOutTypeList);
        listMap.put("countryList", countryDao.selectList(null));


        return SingleResult.success(listMap);
    }

    @Override
    public SingleResult addInitByStorageId(Long id) {
//        List<StorageShelfDo> shelfList = storageShelfDao.selectList(new QueryWrapper<StorageShelfDo>().eq("storage_id", id));
        List<Map> resList = new ArrayList<>();
//        for (StorageShelfDo et : shelfList) {
//            List<StoragePositionDo> positionList = storagePositionDao.selectList(new QueryWrapper<StoragePositionDo>().eq("shelf_id", et.getId()));
//            for (StoragePositionDo pt : positionList.stream()
//                    .filter(storagePositionDo -> StringUtils.isNotBlank(storagePositionDo.getPositionName()))
//                    .sorted(new Comparator<StoragePositionDo>() {
//                @Override
//                public int compare(StoragePositionDo o1, StoragePositionDo o2) {
//                    return o1.getPositionName().compareTo(o2.getPositionName());
//                }
//            }).collect(Collectors.toList())) {
//                Map map = new HashMap();
//                map.put("id", pt.getId());
//                map.put("value", pt.getPositionName());
//                resList.add(map);
//            }
//        }
        List<StoragePreviewDto> list = storagePositionDao.getPositionByStorageId(id, null);
        //按货架 区分
        Map<String, List<StoragePreviewDto>> previewMapList = list.stream().collect(Collectors.groupingBy(i -> i.getShelfId() + "-" + i.getShelfSort()));
        Set<String> keySet = previewMapList.keySet();
        keySet.stream().sorted(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if ("null".equals(o1.split("-")[1]) && !"null".equals(o2.split("-")[2])) {
                    return 1;
                } else if ("null".equals(o2.split("-")[2]) && !"null".equals(o2.split("-")[1])) {
                    return -1;
                } else {
                    return Long.parseLong(o1.split("-")[1]) > Long.parseLong(o2.split("-")[1]) ? 1 : -1;
                }
            }
        });
        for (String key : keySet) {
            List<StoragePreviewDto> shelfPositionList = previewMapList.get(key);
            for (StoragePreviewDto dto : shelfPositionList) {
                Map map = new HashMap();
                map.put("id", dto.getId());
                map.put("value", dto.getPositionName());
                map.put("capacityPercent", dto.getCapacityPercent());
                resList.add(map);
            }
        }
        return SingleResult.success(resList);
    }

    @Override
    public OrderInputAddReq add(OrderInputAddReq req, Long userId, Long companyId) {
        OrderInputDo entityDo = new OrderInputDo();
        BeanUtils.copyProperties(req, entityDo);
        if (req.getCompanyId() == null) {
            throw new BizException(SysConstant.Error_Company);
        }
        entityDo.setStatus(DicBusinessItemConstant.inCreateState);
        if (req.getFbaTurn() == 1) {
            //操作附件
            fileService.uploadFile(req.getFbaFileId());
        }
        handlerAddBefore(entityDo, userId);
        entityDo.setUsdRate(productOutService.getRate("usdRate"));
        entityDo.setJpyRate(productOutService.getRate("jpyRate"));
        dao.insert(entityDo);
        //操作日志
        operateRecordDao.operateAddRecord(SysConstant.OPERATE_CREATE_INPUT, entityDo.getId(), userId, 2);

//        operateRecord("创建了一条入库单", entityDo, userId);

        Float volume = 0F;

        if (!CollectionUtils.isEmpty(req.getPackageList())) {
            for (OrderInputPackageAdd packageAdd : req.getPackageList()) {
                OrderInputPackageDo packageDo = new OrderInputPackageDo();
                packageDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                packageDo.setPackageLenght(packageAdd.getPackageLenght());
                packageDo.setPackageWidth(packageAdd.getPackageWidth());
                packageDo.setPackageHeight(packageAdd.getPackageHeight());
                packageDo.setPackageWeight(packageAdd.getPackageWeight());
                packageDo.setPackageCount(packageAdd.getPackageCount());
                packageDo.setOrderInputId(entityDo.getId());
                orderInputPackageDao.insert(packageDo);
                if (req.getCarriageType() == 0 || req.getCarriageType() == 2) {
                    volume += packageDo.getPackageHeight() * packageDo.getPackageLenght() * packageDo.getPackageWidth() * packageDo.getPackageCount();
                }
                if (!CollectionUtils.isEmpty(packageAdd.getProductDetailList())) {
                    for (OrderInputProductAdd productAdd : packageAdd.getProductDetailList()) {
                        OrderInputProductDo productDo = new OrderInputProductDo();
                        productDo.setOrderInputId(entityDo.getId());
                        productDo.setPackageId(packageDo.getId());
                        productDo.setProductId(productAdd.getProductId());
                        productDo.setCount(productAdd.getCount());
                        orderInputProductDao.insert(productDo);
                        if (req.getCarriageType() == 1) {
                            ProductInfoDo productInfoDo = productInfoDao.selectById(productDo.getProductId());
                            if (productInfoDo != null) {
                                volume += productInfoDo.getHeight() * productInfoDo.getWidth() * productInfoDo.getLength() * productDo.getCount() * packageDo.getPackageCount();
                            }
                        }
                    }
                }
            }
        }
        entityDo.setOrderInputNumber(OrderCodeUtil.getOrderInputNumber(entityDo.getId()));
        entityDo.setVolume(new BigDecimal(volume / 1000000).setScale(2, RoundingMode.HALF_UP).floatValue());
        dao.updateById(entityDo);
        return req;
    }


    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(OrderInputDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(OrderInputDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult markIn(InputOrderMarkSingleReq req, Long userId) {
//        LambdaQueryWrapper<OrderInputDo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(OrderInputDo::getOrderInputNumber, req.getOrderInputNumber());
        OrderInputDo orderInputDo = dao.selectById(req.getId());

        if (orderInputDo == null) {
            throw new BizException(SysConstant.Order_NotExist1);
        }

        LambdaQueryWrapper<OrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
        List<OrderInputPackageDo> inputPackageDoList = orderInputPackageDao.selectList(packageDoLambdaQueryWrapper);

        List<OrderInputProductDo> productDoList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(inputPackageDoList)) {
            for (OrderInputPackageDo orderInputPackageDo : inputPackageDoList) {
                LambdaQueryWrapper<OrderInputProductDo> inputProductDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                inputProductDoLambdaQueryWrapper.eq(OrderInputProductDo::getPackageId, orderInputPackageDo.getId());
                List<OrderInputProductDo> productList = orderInputProductDao.selectList(inputProductDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(productList)) {
                    productDoList.addAll(productList);
                }
            }
        }

        Map<Long, InputOrderMarkProductReq> map = handlerProductDoListToMap(req.getProductInfo());

        if (!CollectionUtils.isEmpty(productDoList)) {
            for (OrderInputProductDo inputProductDo : productDoList) {
                OrderInputPackageDo inputPackageDo = orderInputPackageDao.selectById(inputProductDo.getPackageId());
                InputOrderMarkProductReq productReq = map.get(inputProductDo.getProductId());
                if (productReq == null) continue;
                //可售包裹----------------------------------------------------------------------
                if (inputProductDo.getCount() * inputPackageDo.getPackageCount() <= productReq.getReceiveCount()) {//申请数量小于等于实际数量
                    inputProductDo.setReceiveCount(inputProductDo.getCount() * inputPackageDo.getPackageCount());
                    orderInputProductDao.updateById(inputProductDo);
                    productReq.setReceiveCount(productReq.getReceiveCount() - inputProductDo.getCount() * inputPackageDo.getPackageCount());
                    map.put(inputProductDo.getProductId(), productReq);
                } else if (inputProductDo.getCount() * inputPackageDo.getPackageCount() > productReq.getReceiveCount()) {
                    inputProductDo.setReceiveCount(productReq.getReceiveCount());
                    orderInputProductDao.updateById(inputProductDo);
                    productReq.setReceiveCount(0);
                    map.put(inputProductDo.getProductId(), productReq);
                }


                //不可售包裹---------------------------------------------------------------------------
                if (inputProductDo.getCount() * inputPackageDo.getPackageCount() <= productReq.getBrokenCount()) {//申请数量小于等于实际数量
                    inputProductDo.setBrokenCount(inputProductDo.getCount() * inputPackageDo.getPackageCount());
                    orderInputProductDao.updateById(inputProductDo);
                    productReq.setBrokenCount(productReq.getBrokenCount() - inputProductDo.getCount() * inputPackageDo.getPackageCount());
                    map.put(inputProductDo.getProductId(), productReq);
                } else if (inputProductDo.getCount() * inputPackageDo.getPackageCount() > productReq.getBrokenCount()) {
                    inputProductDo.setBrokenCount(productReq.getBrokenCount());
                    orderInputProductDao.updateById(inputProductDo);
                    productReq.setBrokenCount(0);
                    map.put(inputProductDo.getProductId(), productReq);
                }
            }


            //处理商品数量超出申请数量情况
            for (int i = productDoList.size() - 1; i >= 0; i--) {
                InputOrderMarkProductReq productReq = map.get(productDoList.get(i).getProductId());
                if (productReq == null) continue;

                if (productReq.getReceiveCount() > 0) {
                    OrderInputProductDo inputProductDo = productDoList.get(i);
                    inputProductDo.setReceiveCount(inputProductDo.getReceiveCount() + productReq.getReceiveCount());
                    orderInputProductDao.updateById(inputProductDo);
                    productReq.setReceiveCount(0);
                    map.put(productDoList.get(i).getProductId(), productReq);
                }

                if (productReq.getBrokenCount() > 0) {
                    OrderInputProductDo inputProductDo = productDoList.get(i);
                    inputProductDo.setBrokenCount(inputProductDo.getBrokenCount() + productReq.getBrokenCount());
                    orderInputProductDao.updateById(inputProductDo);
                    productReq.setBrokenCount(0);
                    map.put(productDoList.get(i).getProductId(), productReq);
                }
            }
        }


        return SingleResult.success();
    }

    @Override
    public SingleResult markInInit(Long id) {
        Map result = new HashMap();
        OrderInputDo orderInputDo = dao.selectById(id);
        if (orderInputDo == null) {
            throw new BizException(SysConstant.Order_NotExist1);
        }
        InputMarkInitRes res = new InputMarkInitRes();
        res.setId(id);
        res.setStorageId(orderInputDo.getStorageId());
        List<InputMarkProduct> productList = new ArrayList<>();

        LambdaQueryWrapper<OrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(OrderInputPackageDo::getOrderInputId, id);
        List<OrderInputPackageDo> orderInputPackageDos = orderInputPackageDao.selectList(packageDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(orderInputPackageDos)) {
            for (OrderInputPackageDo orderInputPackageDo : orderInputPackageDos) {
                LambdaQueryWrapper<OrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(OrderInputProductDo::getPackageId, orderInputPackageDo.getId());
                List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(productDoList)) {
                    for (OrderInputProductDo inputProductDo : productDoList) {
                        InputMarkProduct markProduct = new InputMarkProduct();
                        markProduct.setProductId(inputProductDo.getProductId());
                        ProductInfoDo productInfoDo = productInfoDao.selectById(inputProductDo.getProductId());
                        if (productInfoDo != null) {
                            markProduct.setProductName(productInfoDo.getProductName());
                            markProduct.setCommoditySku(productInfoDo.getCommoditySku());
                            markProduct.setStorageSku(productInfoDo.getStorageSku());
                        }
                        markProduct.setBrokenCount(inputProductDo.getBrokenCount());
                        markProduct.setReceiveCount(inputProductDo.getReceiveCount());
                        markProduct.setCount(inputProductDo.getCount() * orderInputPackageDo.getPackageCount());
                        productList.add(markProduct);
                    }
                }
            }
        }

        res.setProductList(handlerDistinctSku(productList));

        result.put("detail", res);
        return SingleResult.success(result);
    }

    private List<InputMarkProduct> handlerDistinctSku(List<InputMarkProduct> productList) {
        List<InputMarkProduct> productsNew = new ArrayList<>();
        Map<Long, List<InputMarkProduct>> collect = productList.stream().collect(Collectors.groupingBy(InputMarkProduct::getProductId));
        if (!CollectionUtils.isEmpty(collect)) {
            for (Long key : collect.keySet()) {
                List<InputMarkProduct> products = collect.get(key);
                if (products.size() == 0) {
                    continue;
                }
                InputMarkProduct inputMarkProduct = products.get(0);

                if (products.size() > 1) {
                    int sum = products.stream().mapToInt(InputMarkProduct::getCount).sum();
                    int rec = products.stream().mapToInt(InputMarkProduct::getReceiveCount).sum();
                    int bro = products.stream().mapToInt(InputMarkProduct::getBrokenCount).sum();

                    inputMarkProduct.setCount(sum);
                    inputMarkProduct.setReceiveCount(rec);
                    inputMarkProduct.setBrokenCount(bro);
                    productsNew.add(inputMarkProduct);
                } else {
                    productsNew.addAll(products);
                }
            }
        }
        return productsNew;
    }

    @Override
    public void allocationStorage(OperateReq req, Long userId) {
        OrderInputDo orderInputDo = dao.selectById(req.getId());
        orderInputDo.setStorageId(req.getStorageId());
        orderInputDo.setUpdateBy(userId);
        orderInputDo.setUpdateTime(new Date());
        if (req.getOperateType() == 1) {//入库并上架
            if (orderInputDo.getStatus() == DicBusinessItemConstant.putaway || orderInputDo.getStatus() == DicBusinessItemConstant.inPutTurnFba) {
                throw new BizException(SysConstant.OrderInput_HadPut);
            }
            orderInputDo.setStatus(DicBusinessItemConstant.putaway);
            orderInputDo.setInputTime(new Date());
            orderInputDo.setInputBy(userId);
            //更新库存数量
            handlerStockCount(req, orderInputDo, userId);
            //异步推送微信公众号
            executor.execute(() -> {
                wxUserService.orderInput(orderInputDo);
            });
        } else if (req.getOperateType() == 2) {//转运fba
            handlerOrderOutput(req, orderInputDo, userId);
        } else if (req.getOperateType() == 3) {
            orderInputDo.setStatus(DicBusinessItemConstant.inPutStorage);
            handlerStockCountInput(req, orderInputDo, userId);
        }
        dao.updateById(orderInputDo);
    }

    private void handlerStockCountInput(OperateReq req, OrderInputDo orderInputDo, Long userId) {
        float volume = 0;
        LambdaQueryWrapper<OrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
        List<OrderInputPackageDo> orderInputPackageDos = orderInputPackageDao.selectList(packageDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(orderInputPackageDos)) {
            for (OrderInputPackageDo orderInputPackageDo : orderInputPackageDos) {
                LambdaQueryWrapper<OrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(OrderInputProductDo::getPackageId, orderInputPackageDo.getId());
                List<OrderInputProductDo> orderInputProductDos = orderInputProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(orderInputProductDos)) {
                    for (OrderInputProductDo orderInputProductDo : orderInputProductDos) {
                        if (orderInputProductDo.getReceiveCount() == 0 && orderInputProductDo.getBrokenCount() == 0)
                            continue;
                        LambdaQueryWrapper<StockRecordDo> stockRecordDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        stockRecordDoLambdaQueryWrapper.eq(StockRecordDo::getProductInfoId, orderInputProductDo.getProductId())
                                .eq(StockRecordDo::getShopId, orderInputDo.getShopId())
                                .eq(StockRecordDo::getStorageId, req.getStorageId());
                        StockRecordDo stockRecordDo = stockRecordDao.selectOne(stockRecordDoLambdaQueryWrapper);
                        if (stockRecordDo == null) {
                            stockRecordDo = new StockRecordDo();
                            stockRecordDo.setStorageId(orderInputDo.getStorageId());
                            stockRecordDo.setCanotSellCount(0);
                            stockRecordDo.setCanSellCount(0);
                            stockRecordDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                            stockRecordDo.setCompanyId(orderInputDo.getCompanyId());
                            stockRecordDo.setProductInfoId(orderInputProductDo.getProductId());
                            stockRecordDo.setShopId(orderInputDo.getShopId());
                            stockRecordDo.setUpdateBy(userId);
                            stockRecordDo.setUpdateTime(new Date());
                            stockRecordDao.insert(stockRecordDo);
                        }
                        ProductInfoDo productInfoDo = productInfoDao.selectById(orderInputProductDo.getProductId());
                        if (productInfoDo != null) {
                            volume = volume + productInfoDo.getHeight() * productInfoDo.getWidth() * productInfoDo.getLength() *
                                    (orderInputProductDo.getReceiveCount() + orderInputProductDo.getBrokenCount()) / 1000000;
                        }
                        volume = new BigDecimal(volume).setScale(2, RoundingMode.HALF_UP).floatValue();
                        orderInputDo.setVolume(volume);
                        updateById(orderInputDo);
                    }
                }
            }
        }
        operateRecordDao.operateAddRecord(SysConstant.OPERATE_INSTORAGE_ORDER, orderInputDo.getId(), userId, 2);

//        operateRecord("入库了订单", orderInputDo, userId);
    }

    /**
     * 转运FBA
     *
     * @param req
     * @param orderInputDo
     * @param userId
     */
    private void handlerOrderOutput(OperateReq req, OrderInputDo orderInputDo, Long userId) {
        OrderOutputDo orderOutputDo = new OrderOutputDo();
//        orderOutputDo.setOrderType(2);//fba转运
        orderOutputDo.setStatus(DicBusinessItemConstant.outCreateState);//已下单
        orderOutputDo.setSendDate(new Date());
        orderOutputDo.setShopId(orderInputDo.getShopId());
        orderOutputDo.setOrderNo("");
        orderOutputDo.setReceiverName("");
        orderOutputDo.setTelPhone("");
        orderOutputDo.setPostCode("");
        orderOutputDo.setArea("");
        orderOutputDo.setAddress("");
        orderOutputDo.setTips("");
        orderOutputDo.setShipFee(0D);
        orderOutputDo.setOutFee(0D);
        orderOutputDo.setOperateFee(0D);
        orderOutputDo.setTaxFee(0D);
        orderOutputDo.setStorageId(orderInputDo.getStorageId());
        orderOutputDo.setTrackId(null);
        orderOutputDo.setCod(null);
        orderOutputDo.setDeliveryDate(null);
        orderOutputDo.setDeliveryTime(null);
        orderOutputDo.setShipmentType(null);
        orderOutputDo.setTrackNumber(null);
        orderOutputDo.setCreateTime(new Date());
        orderOutputDo.setCreateBy(userId);
        orderOutputDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
        orderOutputDao.insert(orderOutputDo);
        orderOutputDo.setOrderOutputNumber(OrderCodeUtil.getOrderOutNumber(orderOutputDo.getId()));
        orderOutputDao.updateById(orderOutputDo);
        //todo package
        //todo product
    }

    private void handlerStockCount(OperateReq req, OrderInputDo orderInputDo, Long userId) {
        float volume = 0;
        LambdaQueryWrapper<OrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
        List<OrderInputPackageDo> orderInputPackageDos = orderInputPackageDao.selectList(packageDoLambdaQueryWrapper);
        List<OrderInputProductDo> productDoList = new ArrayList<>();//保存所有包裹下的产品
        if (!CollectionUtils.isEmpty(orderInputPackageDos)) {
            for (OrderInputPackageDo orderInputPackageDo : orderInputPackageDos) {
                LambdaQueryWrapper<OrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(OrderInputProductDo::getPackageId, orderInputPackageDo.getId());
                List<OrderInputProductDo> orderInputProductDos = orderInputProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(orderInputProductDos)) {
                    productDoList.addAll(orderInputProductDos);
                    for (OrderInputProductDo orderInputProductDo : orderInputProductDos) {
                        if (orderInputProductDo.getReceiveCount() == 0 && orderInputProductDo.getBrokenCount() == 0)
                            continue;
                        LambdaQueryWrapper<StockRecordDo> stockRecordDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        stockRecordDoLambdaQueryWrapper.eq(StockRecordDo::getProductInfoId, orderInputProductDo.getProductId())
                                .eq(StockRecordDo::getShopId, orderInputDo.getShopId())
                                .eq(StockRecordDo::getStorageId, req.getStorageId());
                        StockRecordDo stockRecordDo = stockRecordDao.selectOne(stockRecordDoLambdaQueryWrapper);
                        if (stockRecordDo != null) {
                            stockRecordDo.setCanSellCount(stockRecordDo.getCanSellCount()
                                    + orderInputProductDo.getReceiveCount());
                            stockRecordDo.setCanotSellCount(stockRecordDo.getCanotSellCount()
                                    + orderInputProductDo.getBrokenCount());
                            stockRecordDo.setUpdateBy(userId);
                            stockRecordDo.setUpdateTime(new Date());
                            stockRecordDao.updateById(stockRecordDo);
                        } else {
                            stockRecordDo = new StockRecordDo();
                            stockRecordDo.setStorageId(orderInputDo.getStorageId());
                            stockRecordDo.setCanotSellCount(orderInputProductDo.getBrokenCount());
                            stockRecordDo.setCanSellCount(orderInputProductDo.getReceiveCount());
                            stockRecordDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                            stockRecordDo.setCompanyId(orderInputDo.getCompanyId());
                            stockRecordDo.setProductInfoId(orderInputProductDo.getProductId());
                            stockRecordDo.setShopId(orderInputDo.getShopId());
                            stockRecordDo.setUpdateBy(userId);
                            stockRecordDo.setUpdateTime(new Date());
                            stockRecordDao.insert(stockRecordDo);
                        }
                        ProductInfoDo productInfoDo = productInfoDao.selectById(orderInputProductDo.getProductId());
                        if (productInfoDo != null) {
                            volume = volume + productInfoDo.getHeight() * productInfoDo.getWidth() * productInfoDo.getLength() *
                                    (orderInputProductDo.getReceiveCount() + orderInputProductDo.getBrokenCount()) / 1000000;
                        }
                        volume = new BigDecimal(volume).setScale(2, RoundingMode.HALF_UP).floatValue();
                        orderInputDo.setVolume(volume);
                        updateById(orderInputDo);
                        stockLogService.saveAutoSendOutLog(orderInputProductDo.getProductId(), orderInputDo.getShopId(), orderInputDo.getStorageId(),
                                orderInputProductDo.getReceiveCount(), stockRecordDo.getCanSellCount(), orderInputDo.getCompanyId(), userId, orderInputDo.getOrderInputNumber());
                        stockLogService.saveAutoSendOutLog(1, orderInputProductDo.getProductId(), orderInputDo.getShopId(), orderInputDo.getStorageId(),
                                orderInputProductDo.getBrokenCount(), stockRecordDo.getCanotSellCount(), orderInputDo.getCompanyId(), userId, orderInputDo.getOrderInputNumber());
                    }
                }
            }
        }

        //库存库位分配情况
        Map<Long, List<InputOrderMarkProductReq>> rackMap = new HashMap<>();
        if (req.getProductInfo() != null) {
            rackMap = req.getProductInfo().stream().collect(Collectors.groupingBy(InputOrderMarkProductReq::getProductId));
        }
        //orderInputProductDos 将入库产品汇总一下 保存到新库存表 先进先出
        Map<Long, List<OrderInputProductDo>> listMap = productDoList.stream().collect(Collectors.groupingBy(OrderInputProductDo::getProductId));
        Set<Long> productIdList = listMap.keySet();

        for (Long productId : productIdList) {
            List<OrderInputProductDo> list = listMap.get(productId);
            ProductStockDo stockDo = new ProductStockDo();
            stockDo.setCompanyId(orderInputDo.getCompanyId());
            stockDo.setCreateBy(userId);
            stockDo.setCreateTime(new Date());
            stockDo.setProductId(productId);
            stockDo.setStorageId(orderInputDo.getStorageId());
            stockDo.setGoodQuantity(list.stream().mapToInt(OrderInputProductDo::getReceiveCount).sum());
            stockDo.setReceiveGoodQuantity(stockDo.getGoodQuantity());
            stockDo.setBadQuantity(list.stream().mapToInt(OrderInputProductDo::getBrokenCount).sum());
            stockDo.setReceiveQuantity(stockDo.getGoodQuantity() + stockDo.getBadQuantity());
            stockDo.setOrderId(orderInputDo.getId());
            stockDo.setOrderType("IB");//入库单
//            stockDo.setShopId(orderInputDo.getShopId());
            if (stockDo.getReceiveQuantity() == 0) {
                continue;
            }
            //单位成本 * 单位体积
            productStockDao.insert(stockDo);

            if (rackMap.get(productId) == null || rackMap.get(productId).get(0).getList().size() == 0) {
                //添加到库位表
                ProductStockRackDo rackDo = new ProductStockRackDo();
                rackDo.setGoodQuantity(stockDo.getGoodQuantity());
                rackDo.setBadQuantity(stockDo.getBadQuantity());
                rackDo.setStockId(stockDo.getId());
                rackDo.setCreateTime(new Date());
                //是否存入备货区
                rackDo.setStore(req.getStore());
                productStockRackDao.insert(rackDo);

                productStockFlowingService.insertFlowing(StaticDict.Product_Flowing_Type.Input.getValue(), orderInputDo.getOrderInputNumber(), orderInputDo.getShopId(), productId, orderInputDo.getStorageId(), rackDo.getGoodQuantity(),
                        rackDo.getBadQuantity(), 0, null, orderInputDo.getCompanyId(), userId, "入库单:" + orderInputDo.getOrderInputNumber() + "入库");
            } else {
                List<InputOrderRackReq> rackReqList = rackMap.get(productId).get(0).getList();
                if (rackReqList.stream().mapToInt(InputOrderRackReq::getAvailNum).sum() != rackMap.get(productId).get(0).getReceiveCount()) {
                    throw new BizException(SysConstant.OrderInput_GoodQuantity_Error);
                }
                if (rackReqList.stream().mapToInt(InputOrderRackReq::getDamageNum).sum() != rackMap.get(productId).get(0).getBrokenCount()) {
                    throw new BizException(SysConstant.OrderInput_BadQuantity_Error);
                }
                StorageDo storageDo = storageDao.selectById(orderInputDo.getStorageId());
                for (InputOrderRackReq rackReq : rackReqList) {
                    ProductStockRackDo rackDo = new ProductStockRackDo();
                    rackDo.setGoodQuantity(rackReq.getAvailNum());
                    rackDo.setBadQuantity(rackReq.getDamageNum());
                    rackDo.setStockId(stockDo.getId());
                    rackDo.setRackId(rackReq.getLocationId());
                    rackDo.setCreateTime(new Date());
                    productStockRackDao.insert(rackDo);

                    //添加库存流水
                    productStockFlowingService.insertFlowing(StaticDict.Product_Flowing_Type.Input.getValue(), orderInputDo.getOrderInputNumber(), orderInputDo.getShopId(), productId, orderInputDo.getStorageId(), rackDo.getGoodQuantity(),
                            rackDo.getBadQuantity(), 0, rackReq.getLocationId(), orderInputDo.getCompanyId(), userId, "入库单:" + orderInputDo.getOrderInputNumber() + "入库");
                    //如果库位的 利用率满了 ，通知到消息中心 去盘点
                    if (rackReq.getLocationId() != null) {
//                        List<StoragePreviewDto> previewDto = storagePositionDao.getPositionByStorageId(req.getStorageId(), rackReq.getLocationId());
//                        if (previewDto.size() == 1 && previewDto.get(0).getCapacityPercent() >= 100) {
                        if (rackReq.getCapacityPercent() >= 100) {
                            messageNoticeService.noticeAdd(StaticDict.Message_Notice_Type.RackMore.getValue(), rackReq.getLocationId(), "库位：" + rackReq.getValue() + "利用率异常", "仓库：" + storageDo.getStorageName() + ", 库位：" + rackReq.getValue() + " 利用率已达：" + MathUtils.numberFormat(rackReq.getCapacityPercent() + "", 2) + "%, 请及时盘点确认", userId, null);
                        }
                    }
                }
            }
        }

        float inputFee = 0f;
        if (volume > 3 && orderInputDo.getCarriageType() != 1) {
            inputFee = volume * (750 + 810);
        } else {
            inputFee = volume * 750;
        }
        if (orderInputDo.getSendType() == 0)
            costService.add(1, orderInputDo.getOrderInputNumber() + "入库费用",
                    orderInputDo.getSeaFee() + orderInputDo.getSeaFee() + inputFee * 1.1
                            + orderInputDo.getClearanceFee() + orderInputDo.getTaxFee(),
                    orderInputDo.getShopId(), orderInputDo.getCompanyId(), orderInputDo.getId());
        operateRecordDao.operateAddRecord(SysConstant.OPERATE_INPUT_ORDER, orderInputDo.getId(), userId, 2);
    }

    @Override
    public SingleResult markInSingleInit(String packageId) {
        Map result = new HashMap();

        OrderInputPackageDo orderInputPackageDo = orderInputPackageDao.selectById(packageId);
        if (orderInputPackageDo == null) {
            throw new BizException(SysConstant.OrderInput_Package_NotExist);
        }
// String orderId = "";
//        Integer orderIndex;
//        if (StringUtils.isNotBlank(packageId)) {
//            orderId = packageId.split("-")[0];
//            orderIndex = Integer.valueOf(packageId.split("-")[1]);
//        }
//        OrderInputDo inputDo = dao.selectById(orderId);
//        QueryWrapper wrapper = new QueryWrapper();
//        wrapper.eq("order_input_id", inputDo.getId());
//        List<OrderInputPackageDo> orderInputPackageDoList = orderInputPackageDao.selectList(wrapper);
//        OrderOutputPackageDo orderInputPackageDo=orderInputPackageDoList.get()
        InputMarkSingleInitRes res = new InputMarkSingleInitRes();
        res.setPackageId(Long.parseLong(packageId));
        List<InputMarkProduct> productList = new ArrayList<>();

        LambdaQueryWrapper<OrderInputProductDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInputProductDo::getPackageId, packageId);
        List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(productDoList)) {
            for (OrderInputProductDo inputProductDo : productDoList) {
                InputMarkProduct markProduct = new InputMarkProduct();
                markProduct.setProductId(inputProductDo.getProductId());
                ProductInfoDo productInfoDo = productInfoDao.selectById(inputProductDo.getProductId());
                if (productInfoDo != null) {
                    markProduct.setProductName(productInfoDo.getProductName());
                    markProduct.setCommoditySku(productInfoDo.getCommoditySku());
                    markProduct.setStorageSku(productInfoDo.getStorageSku());
                }
                markProduct.setBrokenCount(inputProductDo.getBrokenCount());
                markProduct.setReceiveCount(inputProductDo.getBrokenCount());
                markProduct.setCount(inputProductDo.getCount());
                productList.add(markProduct);
            }
        }
        res.setProductList(productList);

        result.put("detail", res);

        return SingleResult.success(result);

    }

    @Override
    public SingleResult storageList() {
        List<Map> storageList = new ArrayList<>();
        List<StorageDo> storageDos = storageService.getBaseMapper().selectList(null);
        if (!CollectionUtils.isEmpty(storageDos)) {
            for (StorageDo storageDo : storageDos) {
                Map map = new HashMap();
                map.put("id", storageDo.getId());
                map.put("value", storageDo.getStorageName());
                storageList.add(map);
            }
        }
        return SingleResult.success(storageList);
    }

    private Map<Long, InputOrderMarkProductReq> handlerProductDoListToMap(List<InputOrderMarkProductReq> productInfo) {
        Map<Long, InputOrderMarkProductReq> map = new HashMap();
        if (!CollectionUtils.isEmpty(productInfo)) {
            for (InputOrderMarkProductReq productReq : productInfo) {
                map.put(productReq.getProductId(), productReq);
            }
        }
        return map;
    }

    @Override
    public SingleResult markInSingle(InputOrderMarkReq req, Long userId) {
        for (InputOrderMarkPackageReq inputOrderMarkPackageReq : req.getPackageReqList()) {
            OrderInputPackageDo orderInputPackageDo = orderInputPackageDao.selectById(inputOrderMarkPackageReq.getPackageId());
            if (orderInputPackageDo == null) continue;

            for (InputOrderMarkProductReq productReq : inputOrderMarkPackageReq.getProductInfo()) {
                LambdaQueryWrapper<OrderInputProductDo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(OrderInputProductDo::getPackageId, orderInputPackageDo.getId()).eq(OrderInputProductDo::getProductId, productReq.getProductId());
                OrderInputProductDo inputProductDo = orderInputProductDao.selectOne(wrapper);
                if (inputProductDo == null) continue;
                inputProductDo.setReceiveCount(productReq.getReceiveCount());
                inputProductDo.setBrokenCount(productReq.getBrokenCount());
                orderInputProductDao.updateById(inputProductDo);
            }

        }

        return SingleResult.success();
    }

    @Override
    public SingleResult<Map> updateInit(Long id, Long currentUserId, Long companyId) {
        Map map = (Map) addInit(currentUserId, companyId).getData();

        OrderInputDo entityDo = dao.selectById(id);
        OderInputDetailRes res = new OderInputDetailRes();

        ShopDo shopDo = shopDao.selectById(entityDo.getShopId());
        if (shopDo != null) {
            res.setShopName(shopDo.getShopName());
        }
        res.setShopId(entityDo.getShopId());
        res.setStorageId(entityDo.getStorageId());
        res.setCompanyId(entityDo.getCompanyId());
        res.setFbaStorageId(entityDo.getFbaStorageId());
        StorageDo storageDo = storageDao.selectById(entityDo.getStorageId());
        if (storageDo != null) {
            res.setStorage(storageDo.getStorageName());
        }
        FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(entityDo.getFbaStorageId());
        if (fbaStorageDo != null) {
            res.setFbaStorage(fbaStorageDo.getFbaCode());
        }
        res.setCountryName(entityDo.getCountryName());
        res.setId(entityDo.getId());
        res.setOrderInputNumber(entityDo.getOrderInputNumber());
        res.setDeliveryDate(entityDo.getDeliveryDate());
        res.setCarriageTrackNo(entityDo.getCarriageTrackNo());
        res.setCarriageType(entityDo.getCarriageType());
        String carriageTypeItemDo = getInitValueMap().get("carriageType").get(entityDo.getCarriageType().intValue());
        if (carriageTypeItemDo != null) {
            res.setCarriageTypeName(carriageTypeItemDo);
        }
        res.setClearFileUrl(fileService.getFilePath(entityDo.getClearFileId()));
        res.setClearFileId(entityDo.getClearFileId());
        res.setSendType(entityDo.getSendType());
//        DicBusinessItemDo sendtypeItemDo = dicBusinessItemDao.selectById(entityDo.getSendType());
        String sendtypeItemDo = getInitValueMap().get("sendType").get(entityDo.getSendType().intValue());
        if (sendtypeItemDo != null) {
            res.setSendTypeName(sendtypeItemDo);
        }
        res.setCarriageTrackNo(entityDo.getCarriageTrackNo());
        res.setFbaTurn(entityDo.getFbaTurn());
        String fbaTurn = getInitValueMap().get("fbaTurn").get(entityDo.getFbaTurn());
        if (fbaTurn != null) {
            res.setFbaTurnName(fbaTurn);
        }
        DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(entityDo.getStatus());
        if (businessItemDo != null) {
            res.setStatus(businessItemDo.getDicItemValue());
        }
        res.setFbaNo(entityDo.getFbaNo());
        res.setFbaPo(entityDo.getFbaPo());
        res.setFbaFileUrl(fileService.getFilePath(entityDo.getFbaFileId()));
        res.setFbaFileId(entityDo.getFbaFileId());
        FileDo fileDo = fileService.getBaseMapper().selectById(entityDo.getFbaFileId());
        if (fileDo != null) {
            res.setFileName(fileDo.getFileName());
        }
        res.setVolume(entityDo.getVolume());
        res.setTips(entityDo.getTips());
        res.setSeaFee(entityDo.getSeaFee());
        res.setClearanceFee(entityDo.getClearanceFee());
        res.setServiceFee(entityDo.getServiceFee());
        res.setTaxFee(entityDo.getTaxFee());
        List<OrderInputPackageDetail> packageList = new ArrayList<>();
        LambdaQueryWrapper<OrderInputPackageDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInputPackageDo::getOrderInputId, entityDo.getId());
        List<OrderInputPackageDo> orderInputPackageDos = orderInputPackageDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(orderInputPackageDos)) {
            for (OrderInputPackageDo packageDo : orderInputPackageDos) {
                OrderInputPackageDetail packageDetail = new OrderInputPackageDetail();
                packageDetail.setId(packageDo.getId());
                packageDetail.setCount(packageDo.getPackageCount());
                packageDetail.setHeight(packageDo.getPackageHeight());
                packageDetail.setLength(packageDo.getPackageLenght());
                packageDetail.setWeight(packageDo.getPackageWeight());
                packageDetail.setWidth(packageDo.getPackageWidth());
                List<OrderInputProductDetail> productAddList = new ArrayList<>();

                LambdaQueryWrapper<OrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(OrderInputProductDo::getOrderInputId, entityDo.getId()).eq(OrderInputProductDo::getPackageId, packageDo.getId());
                List<OrderInputProductDo> orderInputProductDos = orderInputProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(orderInputProductDos)) {
                    for (OrderInputProductDo productDo : orderInputProductDos) {
                        OrderInputProductDetail productDetail = new OrderInputProductDetail();
                        ProductInfoDo productInfoDo = productInfoDao.selectById(productDo.getProductId());
                        if (productInfoDo != null) {
                            productDetail.setProductId(productInfoDo.getId());
                            productDetail.setCount(productDo.getCount());
                            productDetail.setCommoditySku(productInfoDo.getCommoditySku());
                            productDetail.setProductName(productInfoDo.getProductName());
                            productDetail.setStorageSku(productInfoDo.getStorageSku());
                            productAddList.add(productDetail);
                        }
                    }
                }
                packageDetail.setProductList(productAddList);

                packageList.add(packageDetail);

            }
        }

        res.setPackageList(packageList);

        //查询日志
        List<OperateRes> operateResList = operateRecordDao.getOperateList(id, 2);
        res.setOperateResList(operateResList);

        map.put("detail", res);
        //包裹信息汇总
        map.put("productList", this.getProductList(id));
        //费用明细
//        map.put("projectResList", this.setPriceInit(entityDo.getCarriageType(), entityDo.getId(), true));
        map.put("projectResList", this.getHeaderContainerProjectRes(entityDo.getId()));

        return SingleResult.success(map);
    }

    //新版费用详情
    public List<HeaderContainerProjectRes> getHeaderContainerProjectRes(Long id) {
        List<ManageHeaderPriceItemDo> itemDoList = this.getHeaderPriceItemDo(id);
        List<HeaderContainerProjectRes> resList = new ArrayList<>();
        for (ManageHeaderPriceItemDo item : itemDoList) {
            HeaderContainerProjectRes res = new HeaderContainerProjectRes();
            if (item.getProjectId() != null) {
                StorageServiceProjectDo projectDo = storageServiceDao.selectById(item.getProjectId());
                if (projectDo == null) {
                    continue;
                }
                res.setProjectName(projectDo.getProjectName());
            } else {
                res.setProjectName(item.getValue());
            }
            res.setCurrencyType(item.getCurrencyType() + "");
            res.setCurrencyTypeName(item.getCurrencyType() == 107L ? "RMB" : (item.getCurrencyType() == 108L ? "JPY" : "USD"));
            res.setPrice(item.getPrice() + item.getTax());
            resList.add(res);
        }
        return resList;
    }

    public List<ManageHeaderPriceItemDo> getHeaderPriceItemDo(Long orderId) {
        HeaderContainerOrderDo containerOrderDo = headerContainerOrderDao.selectOne(new LambdaQueryWrapper<HeaderContainerOrderDo>()
                .eq(HeaderContainerOrderDo::getFirstVesselOrderId, orderId));
        if (containerOrderDo == null) {
            return new ArrayList<>();
        }

        ManageBillDo billDo = null;
        if (containerOrderDo.getBillId() != null) {
            billDo = manageBillDao.selectById(containerOrderDo.getBillId());
        } else {
            //根据orderId 获取 柜号 再获取账单
            HeaderContainerDo headerContainerDo = headerContainerDao.getHeaderByOrderId(orderId);
            if (headerContainerDo == null) {
                return new ArrayList<>();
            }
//            billDo = manageBillDao.getBillByHeaderId(headerContainerDo.getId());
        }
        if (billDo == null) {
            return new ArrayList<>();
        }
        return manageHeaderPriceItemDao.selectList(new LambdaQueryWrapper<ManageHeaderPriceItemDo>()
                .eq(ManageHeaderPriceItemDo::getBillId, billDo.getId())
                .eq(ManageHeaderPriceItemDo::getType, "beginBill"));
    }

    //包裹信息汇总
    public List<InputMarkProduct> getProductList(Long id) {
        List<InputMarkProduct> productList = new ArrayList<>();

        LambdaQueryWrapper<OrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(OrderInputPackageDo::getOrderInputId, id);
        List<OrderInputPackageDo> orderInputPackageDos = orderInputPackageDao.selectList(packageDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(orderInputPackageDos)) {
            for (OrderInputPackageDo orderInputPackageDo : orderInputPackageDos) {
                LambdaQueryWrapper<OrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(OrderInputProductDo::getPackageId, orderInputPackageDo.getId());
                List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(productDoList)) {
                    for (OrderInputProductDo inputProductDo : productDoList) {
                        InputMarkProduct markProduct = new InputMarkProduct();
                        markProduct.setProductId(inputProductDo.getProductId());
                        ProductInfoDo productInfoDo = productInfoDao.selectById(inputProductDo.getProductId());
                        if (productInfoDo != null) {
                            markProduct.setProductName(productInfoDo.getProductName());
                            markProduct.setCommoditySku(productInfoDo.getCommoditySku());
                            markProduct.setStorageSku(productInfoDo.getStorageSku());
                        }
                        markProduct.setBrokenCount(inputProductDo.getBrokenCount());
                        markProduct.setReceiveCount(inputProductDo.getReceiveCount());
                        markProduct.setCount(inputProductDo.getCount() * orderInputPackageDo.getPackageCount());
                        productList.add(markProduct);
                    }
                }
            }
        }
        return handlerDistinctSku(productList);
    }

    @Override
    public OrderInputUpdateReq update(OrderInputUpdateReq req, Long userId) {
        OrderInputDo entityDo = dao.selectById(req.getId());
        if (req.getFbaFileId() == null) req.setFbaFileId(0L);
        if (req.getClearFileId() == null) req.setClearFileId(0L);
        if (entityDo.getFbaFileId() == null) entityDo.setFbaFileId(0L);
        if (entityDo.getClearFileId() == null) entityDo.setClearFileId(0L);
        if (req.getFbaTurn() == 1 && !req.getFbaFileId().equals(entityDo.getFbaFileId())) {
            fileService.uploadFile2(req.getFbaFileId(), entityDo.getFbaFileId());
            fileService.deleteFile(entityDo.getFbaFileId());
        }
        if (req.getSendType() == 1 && !req.getClearFileId().equals(entityDo.getClearFileId())) {
            fileService.uploadFile2(req.getClearFileId(), entityDo.getClearFileId());
            fileService.deleteFile(entityDo.getClearFileId());
        }
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);

        //已上架 之前的状态可以修改
        if (entityDo.getStatus() < DicBusinessItemConstant.putaway) {
            LambdaQueryWrapper<OrderInputPackageDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderInputPackageDo::getOrderInputId, entityDo.getId());
            orderInputPackageDao.delete(wrapper);

            LambdaQueryWrapper<OrderInputProductDo> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.eq(OrderInputProductDo::getOrderInputId, entityDo.getId());
            orderInputProductDao.delete(productWrapper);
            Float volume = 0F;
            if (!CollectionUtils.isEmpty(req.getPackageList())) {
                for (OrderInputPackageAdd packageAdd : req.getPackageList()) {
                    OrderInputPackageDo packageDo = new OrderInputPackageDo();
                    packageDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                    packageDo.setPackageLenght(packageAdd.getPackageLenght());
                    packageDo.setPackageWidth(packageAdd.getPackageWidth());
                    packageDo.setPackageHeight(packageAdd.getPackageHeight());
                    packageDo.setPackageWeight(packageAdd.getPackageWeight());
                    packageDo.setPackageCount(packageAdd.getPackageCount());
                    packageDo.setOrderInputId(entityDo.getId());
                    orderInputPackageDao.insert(packageDo);
                    if (!CollectionUtils.isEmpty(packageAdd.getProductList())) {
                        for (OrderInputProductAdd productAdd : packageAdd.getProductList()) {
                            OrderInputProductDo productDo = new OrderInputProductDo();
                            productDo.setOrderInputId(entityDo.getId());
                            productDo.setPackageId(packageDo.getId());
                            productDo.setProductId(productAdd.getProductId());
                            productDo.setCount(productAdd.getCount());
                            orderInputProductDao.insert(productDo);
                            ProductInfoDo productInfoDo = productInfoDao.selectById(productDo.getProductId());
                            if (productInfoDo != null) {
                                volume += productInfoDo.getHeight() * productInfoDo.getWidth() * productInfoDo.getLength() * productDo.getCount() * packageDo.getPackageCount();
                            }
                        }
                    }
                }
            }
            entityDo.setVolume(new BigDecimal(volume / 1000000).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
            dao.updateById(entityDo);
        }
        return req;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(OrderInputDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }


    @Override
    public int delete(Long id, Long userId) {
        OrderInputDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        dao.deleteById(id);
        //删除从表
        LambdaQueryWrapper<OrderInputPackageDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInputPackageDo::getOrderInputId, id);
        orderInputPackageDao.delete(wrapper);
        if (entityDo.getIsContainer() == 1) {
            headerContainerOrderDao.delete(new LambdaQueryWrapper<HeaderContainerOrderDo>().eq(HeaderContainerOrderDo::getFirstVesselOrderId, id));
        }
        LambdaQueryWrapper<OrderInputProductDo> productWrapper = new LambdaQueryWrapper<>();
        productWrapper.eq(OrderInputProductDo::getOrderInputId, id);
        orderInputProductDao.delete(productWrapper);
        return 1;
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(OrderInputDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public OderInputDetailRes detail(Long id) {
        OrderInputDo entityDo = dao.selectById(id);
        OderInputDetailRes res = new OderInputDetailRes();
        ShopDo shopDo = shopDao.selectById(entityDo.getShopId());
        if (shopDo != null) {
            res.setShopName(shopDo.getShopName());
        }
        res.setShopId(entityDo.getShopId());
        res.setStorageId(entityDo.getStorageId());
        res.setCompanyId(entityDo.getCompanyId());
        StorageDo storageDo = storageDao.selectById(entityDo.getStorageId());
        if (storageDo != null) {
            res.setStorage(storageDo.getStorageName());
        }
        FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(entityDo.getFbaStorageId());
        if (fbaStorageDo != null) {
            res.setFbaStorage(fbaStorageDo.getFbaCode());
        }
        res.setId(entityDo.getId());
        res.setOrderInputNumber(entityDo.getOrderInputNumber());
        res.setDeliveryDate(entityDo.getDeliveryDate());
        res.setCarriageTrackNo(entityDo.getCarriageTrackNo());
        res.setCarriageType(entityDo.getCarriageType());
        res.setCountryName(entityDo.getCountryName());

//        DicBusinessItemDo carriageTypeItemDo = dicBusinessItemDao.selectById(entityDo.getCarriageType());
        String carriageTypeItemDo = getInitValueMap().get("carriageType").get(entityDo.getCarriageType().intValue());
        if (carriageTypeItemDo != null) {
            res.setCarriageTypeName(carriageTypeItemDo);
        }
        res.setSendType(entityDo.getSendType());
//        DicBusinessItemDo sendtypeItemDo = dicBusinessItemDao.selectById(entityDo.getSendType());
        String sendtypeItemDo = getInitValueMap().get("sendType").get(entityDo.getSendType().intValue());
        if (sendtypeItemDo != null) {
            res.setSendTypeName(sendtypeItemDo);
        }
        res.setCarriageTrackNo(entityDo.getCarriageTrackNo());
        res.setFbaTurn(entityDo.getFbaTurn());
        String fbaTurn = getInitValueMap().get("fbaTurn").get(entityDo.getFbaTurn());
        if (fbaTurn != null) {
            res.setFbaTurnName(fbaTurn);
        }
        res.setFbaNo(entityDo.getFbaNo());
        res.setFbaPo(entityDo.getFbaPo());
        res.setFbaFileUrl(fileService.getFilePath(entityDo.getFbaFileId()));
        res.setFbaFileId(entityDo.getFbaFileId());
        res.setClearFileUrl(fileService.getFilePath(entityDo.getClearFileId()));
        res.setClearFileId(entityDo.getClearFileId());
        FileDo fileDo = fileService.getBaseMapper().selectById(entityDo.getFbaFileId());
        if (fileDo != null) {
            res.setFileName(fileDo.getFileName());
        }
        res.setVolume(entityDo.getVolume());
        res.setTips(entityDo.getTips());
        res.setSeaFee(entityDo.getSeaFee());
        res.setClearanceFee(entityDo.getClearanceFee());
        res.setServiceFee(entityDo.getServiceFee());
        res.setTaxFee(entityDo.getTaxFee());
        List<OrderInputPackageDetail> packageList = new ArrayList<>();
        LambdaQueryWrapper<OrderInputPackageDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInputPackageDo::getOrderInputId, entityDo.getId());
        List<OrderInputPackageDo> orderInputPackageDos = orderInputPackageDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(orderInputPackageDos)) {
            for (OrderInputPackageDo packageDo : orderInputPackageDos) {
                OrderInputPackageDetail packageDetail = new OrderInputPackageDetail();
                packageDetail.setId(packageDo.getId());
                packageDetail.setCount(packageDo.getPackageCount());
                packageDetail.setHeight(packageDo.getPackageHeight());
                packageDetail.setLength(packageDo.getPackageLenght());
                packageDetail.setWeight(packageDo.getPackageWeight());
                packageDetail.setWidth(packageDo.getPackageWidth());
                List<OrderInputProductDetail> productAddList = new ArrayList<>();

                LambdaQueryWrapper<OrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(OrderInputProductDo::getOrderInputId, entityDo.getId()).eq(OrderInputProductDo::getPackageId, packageDo.getId());
                List<OrderInputProductDo> orderInputProductDos = orderInputProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(orderInputProductDos)) {
                    for (OrderInputProductDo productDo : orderInputProductDos) {
                        OrderInputProductDetail productDetail = new OrderInputProductDetail();
                        ProductInfoDo productInfoDo = productInfoDao.selectById(productDo.getProductId());
                        if (productInfoDo != null) {
                            BeanUtils.copyProperties(productInfoDo, productDetail);
                            productDetail.setProductId(productInfoDo.getId());
                            productDetail.setCount(productDo.getCount());
//                            productDetail.setCommoditySku(productInfoDo.getCommoditySku());
//                            productDetail.setProductName(productInfoDo.getProductName());
//                            productDetail.setStorageSku(productInfoDo.getStorageSku());
//                            productDetail.setCommodityName(productInfoDo.getCommodityName());
                            productAddList.add(productDetail);
                        }
                    }
                }
                packageDetail.setProductList(productAddList);

                packageList.add(packageDetail);

            }
        }
        //查询日志
        List<OperateRes> operateResList = operateRecordDao.getOperateList(id, 2);
        res.setOperateResList(operateResList);
        res.setPackageList(packageList);
        return res;
    }

    @Override
    public SingleResult auditInit() {
        List<Map> statusList = new ArrayList<>();
        Map map = new HashMap();
        map.put("id", DicBusinessItemConstant.inReject);
        DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(DicBusinessItemConstant.inReject);
        if (businessItemDo != null) {
            map.put("value", businessItemDo.getDicItemValue());
        } else {
            map.put("value", "问题件");
        }

        statusList.add(map);

        map = new HashMap();
        map.put("id", DicBusinessItemConstant.audited);
        DicBusinessItemDo businessItemDo2 = dicBusinessItemDao.selectById(DicBusinessItemConstant.audited);
        if (businessItemDo != null) {
            map.put("value", businessItemDo2.getDicItemValue());
        } else {
            map.put("value", "已审核");
        }
        statusList.add(map);
        return SingleResult.success(statusList);
    }

    @Override
    public SingleResult auditStatusInit() {
        return SingleResult.success(dicBusinessItemService.getDicItemList(DicBusinessConstant.inPutStatus));
    }

    @Override
    public SingleResult setUpCost(SetUpCostReq req, Long userId) {
        OrderInputDo orderInputDo = dao.selectById(req.getId());
        orderInputDo.setClearanceFee(req.getClearanceFee());
        orderInputDo.setSeaFee(req.getSeaFee());
        orderInputDo.setServiceFee(req.getServiceFee());
        orderInputDo.setTaxFee(req.getTaxFee());
        orderInputDo.setUpdateBy(userId);
        orderInputDo.setUpdateTime(new Date());
        dao.updateById(orderInputDo);
        return SingleResult.success();
    }

    @Override
    public SingleResult audit(AuditReq req, Long userId) {
        OrderInputDo orderInputDo = dao.selectById(req.getId());
        long oldStatus = orderInputDo.getStatus();
        orderInputDo.setStatus(req.getStatusId());
        orderInputDo.setTips(req.getRemarks());
        orderInputDo.setUpdateBy(userId);
        orderInputDo.setUpdateTime(new Date());
        dao.updateById(orderInputDo);

        this.rollBack(req.getId(), userId, oldStatus);
        String statusStr = "";
        DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(orderInputDo.getStatus());
        if (businessItemDo != null) {
            statusStr = businessItemDo.getDicItemValue();
        }
        operateRecordDao.operateAddRecord(SysConstant.OPERATE_UPDATE_FBA_ORDER_STATUS, orderInputDo.getId(), userId, 2);

//        operateRecord("修改该了订单状态:" + statusStr, orderInputDo, userId);

        return SingleResult.success();
    }
//
//    private void operateRecord(String content, OrderInputDo orderInputDo, Long userId) {
//        OperateRecordDo operateRecordDo = new OperateRecordDo();
//        operateRecordDo.setOperateTime(new Date());
//        operateRecordDo.setContent(content);
//        operateRecordDo.setOperateBy(userId);
//        operateRecordDo.setType(2);
//        operateRecordDo.setThirdId(orderInputDo.getId());
//        operateRecordDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
//        operateRecordDao.insert(operateRecordDo);
//    }

    private Map<String, Map<Integer, String>> getInitValueMap() {

        Map<String, Map<Integer, String>> result = new HashMap<>();

        Map<Integer, String> carriageType = new HashMap();
        carriageType.put(0, "散货");
        carriageType.put(1, "整柜");
        carriageType.put(2, "空运");

        Map<Integer, String> sendType = new HashMap();
        sendType.put(0, "自发头程");
        sendType.put(1, "筋斗云头程");
        sendType.put(2, "退货入库");

        Map<Integer, String> fbaTurn = new HashMap();
        fbaTurn.put(0, "否");
        fbaTurn.put(1, "是");

        Map<Integer, String> status = new HashMap();
        status.put(-1, "驳回");
        status.put(0, "已下单");
        status.put(1, "已审核");
        status.put(2, "待入库");
        status.put(3, "已入库");
        status.put(4, "已上架");

        result.put("carriageType", carriageType);
        result.put("sendType", sendType);
        result.put("fbaTurn", fbaTurn);
        result.put("status", status);

        return result;
    }

    @Override
    public SingleResult pageInit(Long userId, Long companyId) {
        Map result = new HashMap();
        result.put("shopList", shopService.selectShopListInit(userId, companyId));

        result.put("storage", storageService.getStorageList());
        //运输方式
        List<LanguageValueEntity> carriageType = new ArrayList<>();
        carriageType.add(new LanguageValueEntity(0, "散货"));
        carriageType.add(new LanguageValueEntity(1, "整柜"));
        carriageType.add(new LanguageValueEntity(2, "空运"));

        result.put("transportTypeList", carriageType);

        //发货方式
        List<LanguageValueEntity> sendType = new ArrayList<>();
        sendType.add(new LanguageValueEntity(0, "自发头程"));
        sendType.add(new LanguageValueEntity(1, "筋斗云头程"));
        result.put("sendOutTypeList", sendType);

        result.put("statusList", dicBusinessItemService.getDicItemList(DicBusinessConstant.inPutStatus));
        return SingleResult.success(result);
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<OrderInputDo> wrapper = queryBuild(map);
        IPage<OrderInputDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<OrderInputPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        result.setMapInfo(census(map));
        return result;
    }

    @Override
    public List<ExcelImportPackageRes> importExcel(MultipartFile file, Long companyId) throws IOException {
        if (file == null) {
            throw new BizException(SysConstant.Pls_Choose_File);
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!GlobalConstants.IMG_TYPE_XLS.equals(suffix.toUpperCase()) &&
                !GlobalConstants.IMG_TYPE_XLSX.equals(suffix.toUpperCase())) {
            throw new BizException(SysConstant.File_Form_Incorrect);
        }
        List<ExcelImportVo> excelImportVoList = ExcelUtils.importExcel(file, 0, 1, ExcelImportVo.class);
        List<ExcelImportPackageRes> packageList = new ArrayList<>();
        Map<Long, List<ExcelImportVo>> map = excelImportVoList.stream().filter(product -> StringUtils.isNotBlank(product.getCommoditySku())).collect(Collectors.groupingBy(ExcelImportVo::getPackageNo));
        if (!CollectionUtils.isEmpty(map)) {
            for (Long packageNo : map.keySet()) {
                List<ExcelImportVo> excelImportVos = map.get(packageNo);
                if (!CollectionUtils.isEmpty(excelImportVos)) {
                    ExcelImportPackageRes packageAdd = new ExcelImportPackageRes();
                    packageAdd.setPackageCount(excelImportVos.get(0).getPackageCount());
                    packageAdd.setPackageHeight(excelImportVos.get(0).getHeight().floatValue());
                    packageAdd.setPackageLenght(excelImportVos.get(0).getLength().floatValue());
                    packageAdd.setPackageWidth(excelImportVos.get(0).getWidth().floatValue());
                    packageAdd.setPackageWeight(excelImportVos.get(0).getWeight().floatValue());

                    List<JSONObject> productAddList = new ArrayList<>();
                    for (ExcelImportVo excelImportVo : excelImportVos) {
                        //商品
                        JSONObject productAdd = new JSONObject();
                        LambdaQueryWrapper<ProductInfoDo> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(ProductInfoDo::getCommoditySku, excelImportVo.getCommoditySku());
                        wrapper.eq(ProductInfoDo::getCompanyId, companyId);
                        ProductInfoDo productInfoDo = productInfoDao.selectOne(wrapper);
                        if (productInfoDo != null) {
                            productAdd.put("productId", productInfoDo.getId());
                            productAdd.put("commoditySku", productInfoDo.getCommoditySku());
                            productAdd.put("productName", productInfoDo.getCommodityName());
                            productAdd.put("createTime", productInfoDo.getCreateTime());
                        } else {
                            productAdd.put("productId", "");
                            productAdd.put("commoditySku", "产品不存在，请检查SKU");
                            productAdd.put("productName", "");
                            productAdd.put("createTime", "");
                        }
                        productAdd.put("count", excelImportVo.getCount());

                        productAddList.add(productAdd);
                    }

                    packageAdd.setProductDetailList(productAddList);

                    packageList.add(packageAdd);
                }
            }
        }

        return packageList;
    }

    //统计信息
    private Map census(Map<String, String> queryMap) {
        List<Map> result = new ArrayList<>();

        Map mapTotal = new HashMap();
        queryMap.put("status", "");
        List<OrderInputDo> list = dao.selectList(queryBuild(queryMap));
        mapTotal.put("count", list.size());
        mapTotal.put("name", "全部");
        mapTotal.put("id", null);
        result.add(mapTotal);

        Map<Long, List<OrderInputDo>> listMap = list.stream().collect(Collectors.groupingBy(OrderInputDo::getStatus));
        LambdaQueryWrapper<DicBusinessItemDo> businessItemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        businessItemDoLambdaQueryWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.inPutStatus);
        List<DicBusinessItemDo> businessItemDoList = dicBusinessItemDao.selectList(businessItemDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(businessItemDoList)) {
            for (DicBusinessItemDo itemDo : businessItemDoList) {
                queryMap.put("status", itemDo.getId() + "");
                Map map = new HashMap();
                if (listMap.get(itemDo.getId()) != null) {
                    map.put("count", listMap.get(itemDo.getId()).size());
                } else {
                    map.put("count", 0);
                }
                map.put("name", StringsUtil.createI18Message(itemDo.getDicItemValue()));
                map.put("id", itemDo.getId());
                result.add(map);
            }
        }
        Map map = new HashMap();
        map.put("census", result);
        return map;
    }

    //查询分页列表之后对列表数据的处理
    private List<OrderInputPageRes> handlerListAfter(List<OrderInputDo> list) {
        List<OrderInputPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (OrderInputDo orderInputDo : list) {
                OrderInputPageRes res = new OrderInputPageRes();
                res.setId(orderInputDo.getId());
                res.setCarriageTrackNo(orderInputDo.getCarriageTrackNo());
                CompanyDo companyDo = companyDao.selectById(orderInputDo.getCompanyId());
                if (companyDo != null) {
                    res.setCompanyName(companyDo.getName());
                    res.setCompanyCode(companyDo.getCompanyCode());
                }
                res.setCreateTime(orderInputDo.getCreateTime());
                res.setDeliveryDate(orderInputDo.getDeliveryDate());
                ShopDo shopDo = shopDao.selectById(orderInputDo.getShopId());
                if (shopDo != null) {
                    res.setShopName(shopDo.getShopName());
                }
                res.setOrderInputNumber(orderInputDo.getOrderInputNumber());
                StorageDo storageDo = storageDao.selectById(orderInputDo.getStorageId());
                if (storageDo != null) {
                    res.setStorage(storageDo.getStorageName());
                }
                res.setTips(orderInputDo.getTips());
                res.setVolume(orderInputDo.getVolume());
                DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(orderInputDo.getStatus());
                if (businessItemDo != null) {
                    res.setStatus(businessItemDo.getDicItemValue());
                }
                String carriageTypeItemDo = getInitValueMap().get("carriageType").get(orderInputDo.getCarriageType().intValue());
                if (carriageTypeItemDo != null) {
                    res.setCarriageType(carriageTypeItemDo);
                }
//        DicBusinessItemDo sendtypeItemDo = dicBusinessItemDao.selectById(entityDo.getSendType());
                String sendtypeItemDo = getInitValueMap().get("sendType").get(orderInputDo.getSendType().intValue());
                if (sendtypeItemDo != null) {
                    res.setSendType(sendtypeItemDo);
                }
                LambdaQueryWrapper<OrderInputPackageDo> packageWrapper = new LambdaQueryWrapper<>();
                packageWrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
                List<OrderInputPackageDo> packageDoList = orderInputPackageDao.selectList(packageWrapper);
                if (packageDoList == null || packageDoList.size() < 1) continue;
                int pacakgeCount = 0, totalCount = 0;
                for (OrderInputPackageDo packageDo : packageDoList) {
                    pacakgeCount = pacakgeCount + packageDo.getPackageCount();
                    LambdaQueryWrapper<OrderInputProductDo> productWrapper = new LambdaQueryWrapper<>();
                    productWrapper.eq(OrderInputProductDo::getPackageId, packageDo.getId());
                    List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(productWrapper);
                    if (productDoList == null || productDoList.size() < 1) continue;
                    for (OrderInputProductDo productDo : productDoList) {
                        totalCount = totalCount + packageDo.getPackageCount() * productDo.getCount();
                    }
                }
                res.setPackageCount(pacakgeCount);
                res.setTotalCount(totalCount);
                result.add(res);
            }
        }
        return result;
    }

    private IPage<OrderInputDo> pageInit(Map<String, String> map) {
        IPage<OrderInputDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<OrderInputDo> queryBuild(Map<String, String> map) {
        QueryWrapper<OrderInputDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.and(i -> i.like("order_input_number", map.get("keyword"))
                    .or().like("carriage_track_no", map.get("keyword"))
                    .or().like("tips", map.get("keyword")));
        }
        if (StringUtils.isNotBlank(map.get("shopId"))) {
            wrapper.eq("shop_id", map.get("shopId"));
        }
        if (StringUtils.isNotBlank(map.get("storageId"))) {
            wrapper.eq("storage_id", map.get("storageId"));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("sendOutType"))) {
            wrapper.eq("send_type", map.get("sendOutType"));
        }
        if (StringUtils.isNotBlank(map.get("transportType"))) {
            wrapper.eq("carriage_type", map.get("transportType"));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("company_id", map.get("companyId"));
        }
        return wrapper.orderByDesc("id");
    }

    @Override
    public void exportPackagePdf(Long id, HttpServletResponse response) {
        OrderInputDo inputDo = dao.selectById(id);
        QueryWrapper wrapper = new QueryWrapper();
        if (inputDo == null) {
            throw new BizException(SysConstant.Order_NotExist1);
        }
        wrapper.eq("order_input_id", id);
        String name = inputDo.getOrderInputNumber() + "_" + TimeUtils.getCurrentDateFormat("HHmmss");
        List<OrderInputPackageDo> packageDoList = orderInputPackageDao.selectList(wrapper);
        List<OrderInputPackagePdfExportDetail> packagePdfExportDetails = new ArrayList<>();
        for (OrderInputPackageDo packageDo : packageDoList) {
            OrderInputPackagePdfExportDetail detail = new OrderInputPackagePdfExportDetail();
            detail.setPackageWeight(packageDo.getPackageWeight());
            detail.setSize((int) packageDo.getPackageLenght() + "*" + (int) packageDo.getPackageWidth() + "*" + (int) packageDo.getPackageHeight());
            detail.setCount(packageDo.getPackageCount());
            wrapper = new QueryWrapper();
            wrapper.eq("package_id", packageDo.getId());
            List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(wrapper);
            if (productDoList.size() < 1) {
                detail.setProductType("含まない");
            } else if (productDoList.size() == 1) {
                detail.setProductType("単一のSKU");
                ProductInfoDo productInfoDo = productInfoDao.selectById(productDoList.get(0).getProductId());
                if (productInfoDo == null) {
                    detail.setCommoditySku("未知");
                    detail.setStorageSku("未知");
                } else {
                    detail.setCommoditySku(productInfoDo.getCommoditySku());
                    detail.setStorageSku(productInfoDo.getStorageSku());
                }
                detail.setSkuCount(productDoList.get(0).getCount());
            } else {
                detail.setProductType("混在のSKU");
            }
            packagePdfExportDetails.add(detail);
        }
        PdfUtils pdfUtils = new PdfUtils(name, response);

        String address = "〒";
        pdfUtils.printPackageCodePDF(inputDo, packagePdfExportDetails, null, inputDo.getCountryName());
    }


    @Override
    public SingleResult exportProductCodePdf(Long id, HttpServletResponse response) {
        OrderInputDo inputDo = dao.selectById(id);
        if (inputDo == null) {
            throw new BizException(SysConstant.Order_NotExist1);
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("order_input_id", id);
        OderInputDetailRes detailRes = detail(id);
        String name = inputDo.getOrderInputNumber() + "_" + TimeUtils.getCurrentDateFormat("HHmmss");
        final int[] count = new int[1];
        if (detailRes.getPackageList() != null && detailRes.getPackageList().size() > 0) {
            detailRes.getPackageList().stream().forEach(packageBean -> {
                if (packageBean.getProductList() != null && packageBean.getProductList().size() > 0) {
                    packageBean.getProductList().stream().forEach(product -> {
                        count[0] = count[0] + packageBean.getCount() * product.getCount();
                    });
                }
            });
        }

        PdfUtils pdfUtils;
        if (count[0] < 50000) {
//            pdfUtils = new PdfUtils(filePath + "/" + name);
            pdfUtils = new PdfUtils(name, response);
            pdfUtils.printProductCodePdf(detailRes);
            return SingleResult.success("下载成功");
        } else {
            return SingleResult.failure("数据量太大，请联系客服操作");
        }
    }


    /**
     * 新版下载产品标
     *
     * @param id
     * @param length
     * @param width
     * @param response
     */
    @Override
    public void printBarCodePdf(Map<String, String> map, Long id, int length, int width, HttpServletResponse response) {
        OrderInputDo inputDo = dao.selectById(id);
        if (inputDo == null) {
            throw new BizException(SysConstant.Order_NotExist1);
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("order_input_id", id);
        OderInputDetailRes detailRes = detail(id);
        final int[] count = new int[1];
        if (detailRes.getPackageList() != null && detailRes.getPackageList().size() > 0) {
            detailRes.getPackageList().stream().forEach(packageBean -> {
                if (packageBean.getProductList() != null && packageBean.getProductList().size() > 0) {
                    packageBean.getProductList().stream().forEach(product -> {
                        count[0] = count[0] + packageBean.getCount() * product.getCount();
                    });
                }
            });
        }
        if (count[0] >= 5000) {
            throw new BizException(SysConstant.OrderInput_Print_TooMuch);
        }
        String name = inputDo.getOrderInputNumber() + "_" + TimeUtils.getCurrentDateFormat("HHmmss");
        if (length == 210 && width == 297) {
            //a4打印 一行三个
            BarCodePdfUtils.orderInputPrintA4(map, detailRes, name, response);
        } else {
            //其他纸张类型 一张一个
            BarCodePdfUtils.orderInputPrint(map, detailRes, length, width, name, response);
        }
    }

    private Map<String, Map<String, String>> fbaRetrunAddInit(Long userId, Long companyId) {

        Map map = new HashMap();
        map.put("storage", storageService.getList(new HashMap<>()));
        //fbaStorage
        List<FbaStorageDo> fbaStorageDos = fbaStorageDao.selectList(null);
        List<Map> fbaStorageList = new ArrayList<>();
        fbaStorageDos.forEach(fbaStorageDo -> {
            Map fbaMap = new HashMap();
            fbaMap.put("id", fbaStorageDo.getId());
            fbaMap.put("code", fbaStorageDo.getFbaCode());
            fbaMap.put("name", fbaStorageDo.getFbaName());
            fbaMap.put("address", fbaStorageDo.getAddress());
            fbaMap.put("postCode", fbaStorageDo.getPostCode());
            fbaMap.put("tel", fbaStorageDo.getTelPhone());
            fbaStorageList.add(fbaMap);
        });
        map.put("fbaStorageList", fbaStorageList);
        return map;
    }

    @Override
    public SingleResult fbaReturnInit(Long id, Long userId) {
        Map result = new HashMap();
        if (id == null) {
            throw new BizException(SysConstant.OrderInput_Return_Error);
        }
        FbaReturnInitRes res = new FbaReturnInitRes();
        OrderInputDo orderInputDo = dao.selectById(id);
        result = fbaRetrunAddInit(userId, orderInputDo.getCompanyId());
        res.setShopId(orderInputDo.getShopId());
        res.setStorageId(orderInputDo.getStorageId());
        ShopDo shopDo = shopDao.selectById(orderInputDo.getShopId());
        if (shopDo != null) {
            res.setShopName(shopDo.getShopName());
        }
        StorageDo storageDo = storageDao.selectById(orderInputDo.getStorageId());
        if (storageDo != null) {
            res.setStorage(storageDo.getStorageName());
        }
        res.setOrderInputNumber(orderInputDo.getOrderInputNumber());
        res.setFbaStorageId(orderInputDo.getFbaStorageId());
        res.setFbaFileId(orderInputDo.getFbaFileId());
        res.setFbaFileUrl(fileService.getFilePath(orderInputDo.getFbaFileId()));
        res.setFbaNo(orderInputDo.getFbaNo());
        FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(orderInputDo.getFbaStorageId());
        if (fbaStorageDo != null) {
            res.setFbaStorage(fbaStorageDo.getFbaCode());
        }
        List<FbaOrderOutputPackageUpdateReq> packageList = new ArrayList<>();

        LambdaQueryWrapper<OrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
        List<OrderInputPackageDo> orderInputPackageDos = orderInputPackageDao.selectList(packageDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(orderInputPackageDos)) {
            int packageCount = 1;
            for (int i = 0; i < orderInputPackageDos.size(); i++) {
                OrderInputPackageDo orderInputPackageDo = orderInputPackageDos.get(i);
                FbaOrderOutputPackageUpdateReq packageDetail = new FbaOrderOutputPackageUpdateReq();
                packageDetail.setWidth((double) orderInputPackageDo.getPackageWidth());
                packageDetail.setWeight((double) orderInputPackageDo.getPackageWeight());
                packageDetail.setLength((double) orderInputPackageDo.getPackageLenght());
                packageDetail.setPackageCount(orderInputPackageDo.getPackageCount());
                packageDetail.setHeight((double) orderInputPackageDo.getPackageHeight());
                packageDetail.setPoNumber(orderInputDo.getFbaPo());
                packageDetail.setTips(orderInputDo.getOrderInputNumber() + "-" + (i + 1));
                packageDetail.setId(orderInputPackageDo.getId());
                packageCount = packageCount + 1;
                List<FbaOrderOutputProductDetail> productDetailList = new ArrayList<>();
                LambdaQueryWrapper<OrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(OrderInputProductDo::getPackageId, orderInputPackageDo.getId());
                List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(productDoList)) {
                    productDoList.forEach(orderInputProductDo -> {
                        FbaOrderOutputProductDetail productDetail = new FbaOrderOutputProductDetail();
                        productDetail.setStorageSku(orderInputProductDo.getCommoditySku());
                        productDetail.setCount(orderInputProductDo.getCount());
                        productDetail.setProductId(orderInputProductDo.getProductId());
                        ProductInfoDo productInfoDo = productInfoDao.selectById(orderInputProductDo.getProductId());
                        if (productInfoDo != null) {
                            productDetail.setStorageSku(productInfoDo.getStorageSku());
                            productDetail.setCommoditySku(productInfoDo.getCommoditySku());
                            productDetail.setCommodityName(productInfoDo.getCommodityName());
                        }
                        productDetailList.add(productDetail);
                    });
                }
                packageDetail.setProductList(productDetailList);
                packageList.add(packageDetail);
            }
        }
        res.setPackageList(packageList);
        result.put("detail", res);
        //入库上架，不收费用
//            if (orderInputDo.getStatus() == DicBusinessItemConstant.inPutStorage) {
//                handlerStockCount(orderInputDo, userId);
//            }
        return SingleResult.success(result);
    }

    @Override
    public SingleResult rollBack(Long id, Long userId, long oldStatus) {
        //先t_stock_record 中的记录
        OrderInputDo orderInputDo = dao.selectById(id);//t_order_input 主数据
        if (orderInputDo == null || oldStatus != DicBusinessItemConstant.putaway || orderInputDo.getStatus() >= DicBusinessItemConstant.inPutTurnFba) {
            return null;
        }
        //获取入库订单的入库产品信息
        List<OrderInputProductDo> orderInputProductDoList = orderInputProductDao.selectList(new QueryWrapper<OrderInputProductDo>().eq("order_input_id", orderInputDo.getId()));
        //获取t_stock_record表中的入库信息
        for (OrderInputProductDo productDo : orderInputProductDoList) {
            QueryWrapper<StockRecordDo> stockRecordDoQueryWrapper = new QueryWrapper<>();
            stockRecordDoQueryWrapper.eq("product_info_id", productDo.getProductId()).eq("shop_id", orderInputDo.getShopId()).eq("storage_id", orderInputDo.getStorageId()).eq("company_id", orderInputDo.getCompanyId());
            //查询每一条产品的入库记录
            StockRecordDo stockRecordDo = stockRecordDao.selectOne(stockRecordDoQueryWrapper);
            if (stockRecordDo == null) {
                throw new BizException(SysConstant.Product_Stock_NotEnough);
            }
            int outCount = 0;
            int outBrokenCount = 0;

            outCount = Math.min(stockRecordDo.getCanSellCount(), productDo.getReceiveCount());
            outBrokenCount = Math.min(stockRecordDo.getCanotSellCount(), productDo.getBrokenCount());
            //扣除原先的库存记录
            stockRecordDo.setCanSellCount(Math.max((stockRecordDo.getCanSellCount() - productDo.getReceiveCount()), 0));
            stockRecordDo.setCanotSellCount(Math.max(stockRecordDo.getCanotSellCount() - productDo.getBrokenCount(), 0));

            stockRecordDao.updateById(stockRecordDo);
            //回滚的 操作日志
            stockLogService.saveAutoSendOutLog(productDo.getProductId(), orderInputDo.getShopId(), orderInputDo.getStorageId(), -outCount, stockRecordDo.getCanSellCount(), orderInputDo.getCompanyId(), userId, orderInputDo.getOrderInputNumber());
            stockLogService.saveAutoSendOutLog(1, productDo.getProductId(), orderInputDo.getShopId(), orderInputDo.getStorageId(), -outBrokenCount, stockRecordDo.getCanotSellCount(), orderInputDo.getCompanyId(), userId, orderInputDo.getOrderInputNumber());
        }
        //新表库存 回滚
        for (OrderInputProductDo orderInputProductDo : orderInputProductDoList) {
            ProductStockDo stockDo = productStockDao.selectOne(new LambdaQueryWrapper<ProductStockDo>()
                    .eq(ProductStockDo::getProductId, orderInputProductDo.getProductId()).eq(ProductStockDo::getOrderId, id)
                    .eq(ProductStockDo::getOrderType, "IB")
                    .eq(ProductStockDo::getStorageId, orderInputDo.getStorageId()));
            if (stockDo == null) {
                throw new BizException(SysConstant.OrderInput_Roll_NotMatch);
            }
            List<ProductStockRackDo> stockRackDoList = productStockRackDao.selectList(new LambdaQueryWrapper<ProductStockRackDo>()
                    .eq(ProductStockRackDo::getStockId, stockDo.getId()));
            int goodQuantity = stockRackDoList.stream().mapToInt(ProductStockRackDo::getGoodQuantity).sum();
            int badQuantity = stockRackDoList.stream().mapToInt(ProductStockRackDo::getBadQuantity).sum();
            if (goodQuantity != orderInputProductDo.getReceiveCount() || badQuantity != orderInputProductDo.getBrokenCount()) {
                throw new BizException(SysConstant.OrderInput_Roll_HadUsed);
            }
            productStockRackDao.delete(new LambdaQueryWrapper<ProductStockRackDo>()
                    .eq(ProductStockRackDo::getStockId, stockDo.getId()));
            //在删除库存主表
            productStockDao.deleteById(stockDo);

            for (ProductStockRackDo stockRackDo : stockRackDoList) {
                //并插入流水 库存流水新
                productStockFlowingService.insertFlowing(StaticDict.Product_Flowing_Type.InputRoll.getValue(), orderInputDo.getOrderInputNumber(), orderInputDo.getShopId(), orderInputProductDo.getProductId(), orderInputDo.getStorageId(), -stockRackDo.getGoodQuantity(),
                        -stockRackDo.getBadQuantity(), 0, stockRackDo.getRackId(), orderInputDo.getCompanyId(), userId, "入库单:" + orderInputDo.getOrderInputNumber() + "库存回滚");
            }
        }

//        orderInputDo.setStatus(DicBusinessItemConstant.inCreateState);
//        baseMapper.updateById(orderInputDo);
        //查询扣款记录
        List<CostRecordDo> costRecordDoList = costRecordDao.selectList(new QueryWrapper<CostRecordDo>().eq("type", 1).eq("company_id", orderInputDo.getCompanyId()).eq("shop_id", orderInputDo.getShopId()).eq("third_id", orderInputDo.getId()).orderByDesc("id"));
        CostRecordDo costRecordDo = null;
        if (!CollectionUtils.isEmpty(costRecordDoList)) {
            costRecordDo = costRecordDoList.get(0);
        }
        if (costRecordDo != null) {
            //退款值账户
//            companyAccountService.costAmount(String.valueOf(orderInputDo.getCompanyId()), -costRecordDo.getCostAmount());
            //删除扣款记录
            costRecordService.add(1, orderInputDo.getOrderInputNumber() + "回滚退还入库费用", -costRecordDo.getCostAmount(), orderInputDo.getShopId(), orderInputDo.getCompanyId(), orderInputDo.getId());
        }
        return SingleResult.success();
    }


    private double numberFormat(double f) {
        BigDecimal b = new BigDecimal(f);
        return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public List<HeaderContainerProjectRes> setPriceInit(long type, long orderId, boolean flag) {
        LambdaQueryWrapper<StorageServiceProjectDo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<DicBusinessItemDo> itemDoList = dicBusinessItemDao.selectList(new LambdaQueryWrapper<DicBusinessItemDo>()
                .eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.headerContainerFeeProjectStatus));
        List<HeaderContainerProjectRes> projectResList = new ArrayList<>();

        for (DicBusinessItemDo itemDo : itemDoList) {
            lambdaQueryWrapper.eq(StorageServiceProjectDo::getType, itemDo.getId());//头程订单
            List<StorageServiceProjectDo> projectDoList = storageServiceDao.selectList(lambdaQueryWrapper);
            for (StorageServiceProjectDo storageServiceProjectDo : projectDoList) {
                if (type == 0) {
                    if (storageServiceProjectDo.getId() != 2 && storageServiceProjectDo.getId() != 4 && storageServiceProjectDo.getId() != 10 &&
                            storageServiceProjectDo.getId() != 11 && storageServiceProjectDo.getId() != 12 && storageServiceProjectDo.getId() != 15) {
                        continue;
                    }
                }
                HeaderContainerProjectRes projectRes = new HeaderContainerProjectRes();
                BeanUtils.copyProperties(storageServiceProjectDo, projectRes);
                projectRes.setPrice(storageServiceProjectDo.getPrice());
                DicBusinessItemDo itemDo1 = dicBusinessItemDao.selectById(storageServiceProjectDo.getCurrencyType());
                if (itemDo1 != null)
                    projectRes.setCurrencyTypeName(itemDo1.getDicItemValue());
                if (storageServiceProjectDo.getId() == 10) {
                    projectRes.setProjectContent("请输入货值(USD)");
                    projectRes.setCurrencyTypeName("USD");
                } else if (storageServiceProjectDo.getId() == 11) {
                    projectRes.setProjectContent("请输入关税比(%)");
                    projectRes.setCurrencyTypeName("%");
                }
                if (type == 0 && storageServiceProjectDo.getId() == 4) {
                    projectRes.setProjectContent("头程费");
                    projectRes.setPrice(700);
                    projectRes.setCurrencyTypeName("RMB");
                }
                LambdaQueryWrapper<HeaderPriceItemDo> itemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                itemDoLambdaQueryWrapper.eq(HeaderPriceItemDo::getOrderInputId, orderId);
                itemDoLambdaQueryWrapper.eq(HeaderPriceItemDo::getProjectId, storageServiceProjectDo.getId());
                HeaderPriceItemDo itemDo2 = headerPriceItemService.getBaseMapper().selectOne(itemDoLambdaQueryWrapper);
                if (flag && itemDo2 == null) {
                    //flag = true 表示展示已添加的费用项目
                    continue;
                }
                if (itemDo2 != null) {
                    projectRes.setPrice(itemDo2.getPrice());
                    projectRes.setTips(itemDo2.getTips());
                }
                projectResList.add(projectRes);
            }
        }
        return projectResList;
    }


    @Override
    public SingleResult setPriceInit(long type, long orderId) {
        OrderInputDo et = dao.selectById(orderId);
        if (et == null) {
            throw new BizException(SysConstant.Order_NotExist1);
        }
        return SingleResult.success(this.setPriceInit(type, orderId, false));
    }

    @Override
    public SingleResult setPriceItem(HeaderFeeSetRequest request) {
        OrderInputDo containerDo = baseMapper.selectById(request.getId());
        if (containerDo == null) {
            throw new BizException(SysConstant.Order_NotExist1);
        }
        headerPriceItemService.savePriceItem(1, request);
        containerDo.setSetPriceFlag(1);
        updateById(containerDo);
        if (containerDo.getSendType() != 1) {//不是筋斗云承运头程
//            containerParentDo.setShipBroker("1");
//            updateById(containerParentDo);
        } else {

        }

        //判断 这条入库单有没有出过库
//        List<ProductOutRecordDo> productOutRecordDoList = productOutRecordDao.selectList(new LambdaQueryWrapper<ProductOutRecordDo>().eq(ProductOutRecordDo::getOrderId, request.getId()));
//        Map<Long, List<ProductOutRecordDo>> listMap = productOutRecordDoList.stream().collect(Collectors.groupingBy(ProductOutRecordDo::getOutId));
//        Set<Long> outIdKeyList = listMap.keySet();
//
//        Map<Long, Double> unitCostMap = new HashMap<>();
//        for (Long aLong : outIdKeyList) {
//            ProductOutDo outDo = productOutDao.selectById(aLong);
//            if (outDo == null) {
//                continue;
//            }
//            ProductInfoDo productInfoDo = productInfoDao.selectById(outDo.getProductId());
//            if (productInfoDo == null) {
//                throw new BizException("产品并不存在");
//            }
//            //一条出库单 的出库记录
//            List<ProductOutRecordDo> recordDoList = productOutRecordDao.selectList(new LambdaQueryWrapper<ProductOutRecordDo>().eq(ProductOutRecordDo::getOutId, aLong));
//            double cost = 0d;
//            for (ProductOutRecordDo recordDo : recordDoList) {
//
//                if (unitCostMap.get(recordDo.getOrderId()) == null) {
//                    //获取入库单的 单位费用 ， 需要再乘以 产品体积
//                    unitCostMap.put(recordDo.getOrderId(), this.getOrderInputUnitCost(recordDo.getOrderId()));
//                }
//                ProductStockDo stockDo = productStockDao.getStockById(recordDo.getStockId());
//                if (stockDo == null) {
//                    throw new BizException("库存记录不存在");
//                }
//                cost = MathUtils.add(cost, MathUtils.mul(unitCostMap.get(recordDo.getOrderId()), productInfoDo.getLength(), productInfoDo.getWidth(), productInfoDo.getHeight(), recordDo.getQuantity()));
//            }
//            //总费用 cost ，然然后计算单位费用
//            outDo.setUnitCost(MathUtils.div(cost, outDo.getQuantity()));
//            productOutDao.updateById(outDo);
//        }
        return SingleResult.success();
    }

    @Override
    public void exportHeaderFeePage(Long orderId, HttpServletResponse response) {
        OrderInputDo orderInputDo = baseMapper.selectById(orderId);
        if (orderInputDo == null) {
            throw new BizException(SysConstant.Order_NotExist1);
        }
        LambdaQueryWrapper<HeaderPriceItemDo> priceItemDoWrapper = new LambdaQueryWrapper<>();
        priceItemDoWrapper.eq(HeaderPriceItemDo::getHeaderId, orderInputDo.getId());
        List<HeaderPriceItemDo> priceItemDoList = headerPriceItemService.getBaseMapper().selectList(priceItemDoWrapper);
        List<HeaderPriceItemPartExportVo> priceItemPartExportVoList = new ArrayList<>();
        if (priceItemDoList == null || priceItemDoList.size() < 1) {
            throw new BizException(SysConstant.OrderInput_Export_Error);
        }
        double totalFee = 0;
        double jpyRate = getRate(0);//头程账单加税点5个点
        double usdRate = getRate(1) + 10;//头程账单加税点1个点
        int index = 0;
        double currentRmdFee = 0;
        for (HeaderPriceItemDo itemDo : priceItemDoList) {
            StorageServiceProjectDo projectDo = storageServiceDao.selectById(itemDo.getProjectId());
            if (projectDo == null) continue;
            HeaderPriceItemPartExportVo partExportVo = new HeaderPriceItemPartExportVo();
            if (orderInputDo.getCarriageType() == 0) {
                partExportVo.setUnit(dicBusinessItemDao.selectById(projectDo.getCurrencyType()).getDicItemValue());
                partExportVo.setProject(projectDo.getProjectContent());
                if (itemDo.getProjectId() == 2) {
                    partExportVo.setPrice(itemDo.getPrice().intValue());
                    partExportVo.setTaxPrice((int) ((double) (itemDo.getPrice() * 0.1D)));
                    partExportVo.setTotalPrice(partExportVo.getPrice() + partExportVo.getTaxPrice());
                    partExportVo.setTips(itemDo.getTips());
                } else if (itemDo.getProjectId() == 10) {//货值
//                    int value = (int) (numberFormat((orderInputDo.getValue() * (1 + orderInputDo.getRate() / 100)) * 0.1 * usdRate / jpyRate));
                    int value = partExportVo.getPrice();
                    partExportVo.setPrice(value);
                    partExportVo.setTotalPrice(value);
                } else if (itemDo.getProjectId() == 11) {//关税
//                    int value = (int) (orderInputDo.getValue() * orderInputDo.getRate() / 100 * usdRate / jpyRate);
                    int value = partExportVo.getPrice();
                    partExportVo.setPrice(value);
                    partExportVo.setTotalPrice(value);
                } else if (itemDo.getProjectId() == 4) {//海运费
                    itemDo.setTips(itemDo.getTips() + " " + orderInputDo.getVolume() + "m³");
                    partExportVo.setPrice((int) (itemDo.getPrice().doubleValue()));
                    partExportVo.setUnit("RMB");
                    projectDo.setCurrencyType(DicBusinessItemConstant.CurrencyTypeRmb + "");
                    partExportVo.setTotalPrice((int) (partExportVo.getPrice() * orderInputDo.getVolume()) + partExportVo.getTaxPrice());
                } else {
                    partExportVo.setPrice((int) (itemDo.getPrice().doubleValue()));
                    partExportVo.setTaxPrice((int) ((double) (itemDo.getPrice() * 0.1D)));
                    partExportVo.setTotalPrice(partExportVo.getPrice() + partExportVo.getTaxPrice());
                }
                partExportVo.setTips(itemDo.getTips());

            } else {
                if (itemDo.getProjectId() == 4 || itemDo.getProjectId() == 16) {
                    partExportVo.setProject(projectDo.getProjectContent() + "(" + orderInputDo.getCarriageTrackNo() + ")");
                } else {
                    partExportVo.setProject(projectDo.getProjectContent());
                }
                if (itemDo.getProjectId() == 10) {
//                    partExportVo.setPrice((int) ((double) (orderInputDo.getValue() * (1 + orderInputDo.getRate() / 100)) * 0.1 * usdRate / jpyRate));
                    partExportVo.setPrice(partExportVo.getPrice());
                } else if (itemDo.getProjectId() == 11) {
//                    partExportVo.setPrice((int) (double) (orderInputDo.getValue() * orderInputDo.getRate() / 100 * usdRate / jpyRate));
                    partExportVo.setPrice(partExportVo.getPrice());

                } else {
                    partExportVo.setPrice(itemDo.getPrice().intValue());
                }
                partExportVo.setProject(projectDo.getProjectContent());
                if (itemDo.getTaxFlag() == 0) {
                    partExportVo.setTaxPrice((int) ((double) (itemDo.getPrice() * 0.1D)));
                }
                partExportVo.setUnit(dicBusinessItemDao.selectById(projectDo.getCurrencyType()).getDicItemValue());
                partExportVo.setTotalPrice(partExportVo.getPrice() + partExportVo.getTaxPrice());
            }
            partExportVo.setTips(itemDo.getTips());
            if (projectDo.getCurrencyType().equals(DicBusinessItemConstant.CurrencyTypeRmb.toString())) {
                currentRmdFee = partExportVo.getTotalPrice();
            } else if (projectDo.getCurrencyType().equals(DicBusinessItemConstant.CurrencyTypeUsd.toString())) {
                currentRmdFee = numberFormat(partExportVo.getTotalPrice() * usdRate);
            } else {
                currentRmdFee = numberFormat(partExportVo.getTotalPrice() * jpyRate);
            }
            totalFee = currentRmdFee + totalFee;
            index++;
            partExportVo.setIndex(index);
            priceItemPartExportVoList.add(partExportVo);
        }
        // 获取模板文件路径
        TemplateExportParams params = new TemplateExportParams(filePath + "头程账单.xlsx");
        //设置sheetName，若不设置该参数，则使用得原本得sheet名称
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", priceItemPartExportVoList);
        data.put("totalFee", numberFormat(totalFee));
        data.put("jpRate", numberFormat(jpyRate));
        data.put("usRate", numberFormat(usdRate));
//        DicBusinessItemDo itemDo = dicBusinessItemDao.selectById(containerDo.getEndPortId());
//        if (itemDo != null)
//            data.put("portJp", itemDo.getDicItemValue());
//        DicBusinessItemDo portCH = dicBusinessItemDao.selectById(containerDo.getStartPortId());
//        if (portCH != null)
//            data.put("portCh", portCH.getDicItemValue());

        // 获取workbook
        Workbook workbook = ExcelExportUtil.exportExcel(params, data);
        try {
            ExcelUtils.downLoadExcel("头程账单", response, workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
        orderInputDo.setSetPriceFlag(2);

    }

    @Override
    public void exportPackageInvoice(Long id, HttpServletResponse responseBody) {
        OrderInputDo orderInputDo = dao.selectById(id);
        if (orderInputDo == null) return;
        List<OrderInputPickupExcelExportVo> orderInputPickupExcelExportVos = new ArrayList<>();
        OrderHeaderContainerExportVo containerExportVo = new OrderHeaderContainerExportVo();
        containerExportVo.setBillLadingNumber("");
        containerExportVo.setInputDate(TimeUtils.formatDate(orderInputDo.getDeleteTime()));
        containerExportVo.setContainerNo(orderInputDo.getCarriageTrackNo());
        containerExportVo.setContainerType(getInitValueMap().get("carriageType").get(orderInputDo.getCarriageType().intValue()));
        int totalPackageCount = 0;

        LambdaQueryWrapper<OrderInputPackageDo> packageDoWrapper = new LambdaQueryWrapper<>();
        packageDoWrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
        List<OrderInputPackageDo> packageDoList = orderInputPackageDao.selectList(packageDoWrapper);
        if (packageDoList.size() < 1) return;
        for (OrderInputPackageDo packageDo : packageDoList) {
            OrderInputPickupExcelExportVo pickupExcelExportVo = new OrderInputPickupExcelExportVo();
            pickupExcelExportVo.setOrderNo(orderInputDo.getOrderInputNumber());
            pickupExcelExportVo.setCompanyCode(companyDao.selectById(orderInputDo.getCompanyId()).getCompanyCode());
            pickupExcelExportVo.setPackageCount(packageDo.getPackageCount());
            pickupExcelExportVo.setPackageLength(packageDo.getPackageLenght() + "(  )");
            pickupExcelExportVo.setPackageWeight(packageDo.getPackageWeight() + "(  )");
            pickupExcelExportVo.setPackageWidth(packageDo.getPackageWidth() + "(  )");
            pickupExcelExportVo.setPackageHeight(packageDo.getPackageHeight() + "(  )");
            totalPackageCount = totalPackageCount + packageDo.getPackageCount();
            LambdaQueryWrapper<OrderInputProductDo> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.eq(OrderInputProductDo::getPackageId, packageDo.getId());
            List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(productWrapper);
            if (productDoList.size() < 1) continue;
            if (productDoList.size() == 1) {
                ProductInfoDo productInfoDo = productInfoDao.selectById(productDoList.get(0).getProductId());
                if (productInfoDo == null) continue;
                pickupExcelExportVo.setCommoditySku(productInfoDo.getCommoditySku());
                pickupExcelExportVo.setStorageSku(productInfoDo.getStorageSku());
                pickupExcelExportVo.setProductCount(productDoList.get(0).getCount());
                //获取该库存 是否有货
                int count = stockRecordDao.selectCount(new LambdaQueryWrapper<StockRecordDo>().eq(StockRecordDo::getStorageId, orderInputDo.getStorageId())
                                .eq(StockRecordDo::getProductInfoId, productInfoDo.getId())
//                        .and(i -> i.gt(StockRecordDo::getCanSellCount, 0).or().gt(StockRecordDo::getCanotSellCount, 0).or().gt(StockRecordDo::getFreezeCount, 0).gt(StockRecordDo::getRepairingCount, 0))
                );
                if (count == 0) {
                    pickupExcelExportVo.setStockType("新品");
                } else {
                    pickupExcelExportVo.setStockType("旧品");
                }
            } else {
                pickupExcelExportVo.setCommoditySku("混装");
                pickupExcelExportVo.setStorageSku("混装");
                pickupExcelExportVo.setProductCount(productDoList.stream().mapToInt(OrderInputProductDo::getCount).sum());
                pickupExcelExportVo.setStockType("混装");
            }
            if (orderInputDo.getFbaTurn() == 0) {
                pickupExcelExportVo.setOperate("上架");
            } else {
                FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(orderInputDo.getFbaStorageId());
                if (fbaStorageDo != null)
                    pickupExcelExportVo.setOperate(fbaStorageDo.getFbaCode());
                else
                    pickupExcelExportVo.setOperate("转运");
            }
            orderInputPickupExcelExportVos.add(pickupExcelExportVo);
        }
        containerExportVo.setTotalCount(totalPackageCount);
        // 获取模板文件路径
        TemplateExportParams params = new TemplateExportParams(filePath + "入库拣货单.xls");
        //设置sheetName，若不设置该参数，则使用得原本得sheet名称
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list1", orderInputPickupExcelExportVos);
        data.put("order", containerExportVo);

        // 获取workbook
        Workbook workbook = ExcelExportUtil.exportExcel(params, data);
        try {
            ExcelUtils.downLoadExcel("入库单拣货", responseBody, workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private double getRate(int type) {
        //实时汇率
        QueryWrapper<ExchangeRateDo> wrapper = new QueryWrapper();
        wrapper.orderByDesc("id");
        wrapper.eq("type", type);
        wrapper.last("limit 1");
        ExchangeRateDo exchangeRateDo = rateDao.selectOne(wrapper);
        return exchangeRateDo.getRate();
    }


    @Override
    public double getOrderInputUnitCost(Long orderId, Long companyId) {
        //获取一个订单的总体积
        float vol = this.getTotalVolByOrderId(orderId);
        //单位成本
        if (vol == 0f) {
            return 0d;
        }
        //计算单位入库成本
        //根据订单id 获取t_header_price_item 表中的费用
        HeaderContainerOrderDo containerOrderDo = headerContainerOrderDao.selectOne(new LambdaQueryWrapper<HeaderContainerOrderDo>()
                .eq(HeaderContainerOrderDo::getFirstVesselOrderId, orderId));
        if (containerOrderDo == null) {
            return 0d;
        }
        HeaderContainerDo headerContainerDo = headerContainerDao.selectById(containerOrderDo.getHeaderContainerId());
        if (headerContainerDo == null) {
            return 0d;
        }
        if (companyId != 1L) {
            ManageBillDo billDo = null;
            if (headerContainerDo.getType() == 0) {
                //拼柜
                billDo = manageBillDao.selectById(containerOrderDo.getBillId());
            } else {
                //整柜
                billDo = manageBillDao.getBillByHeaderId(headerContainerDo.getId());
            }
            if (billDo == null) {
                return 0d;
            }
            //计算这个账单下有多少订单 ，按体积均摊
            List<Long> orderIds;
            ManageHeaderRateDo headerRateDo;
            if (billDo.getBatch() == 0) {
                //散货 或者单个柜子录入
                orderIds = headerContainerOrderDao.selectList(new LambdaQueryWrapper<HeaderContainerOrderDo>()
                        .eq(HeaderContainerOrderDo::getBillId, billDo.getId())).stream().map(HeaderContainerOrderDo::getFirstVesselOrderId).collect(Collectors.toList());
                //汇率
                headerRateDo = manageHeaderRateDao.selectOne(new LambdaQueryWrapper<ManageHeaderRateDo>()
                        .eq(ManageHeaderRateDo::getHeaderId, headerContainerDo.getId()).eq(ManageHeaderRateDo::getType, "header"));
            } else {
                //批量整柜录入
                orderIds = dao.getOrderIdByBillId(billDo.getId());
                headerRateDo = manageHeaderRateDao.selectOne(new LambdaQueryWrapper<ManageHeaderRateDo>()
                        .eq(ManageHeaderRateDo::getHeaderId, billDo.getId()).eq(ManageHeaderRateDo::getType, "bill"));
            }
            if (headerRateDo == null) {
                log.error("订单id:" + orderId + "未匹配到汇率");
                return 0d;
            }
            float totalVol = 0f;
            //计算账单下商品总体积
            for (Long id : orderIds) {
                totalVol = MathUtils.add(totalVol, this.getTotalVolByOrderId(id));
            }
            if (totalVol == 0f) {
                return 0d;
            }
            //账单的 项目金额
            List<ManageHeaderPriceItemDo> headerPriceItemDoList = manageHeaderPriceItemDao.selectList(new LambdaQueryWrapper<ManageHeaderPriceItemDo>()
                    .eq(ManageHeaderPriceItemDo::getBillId, billDo.getId())
                    .eq(ManageHeaderPriceItemDo::getType, "beginBill"));
            //转换成美金
            return this.getUnitCostByPriceItem(headerPriceItemDoList, headerRateDo, vol, totalVol);
        }
        else {
            //自家公司 去获取成本 按成本 体积 均摊成本
            //通过orderId 获取到头程t_header_container 的id ，通过headerId 获取到 t_manage_bill的id
           //录入成本时 是不分公司的， 所以计算这个柜子下的总体积 让后均摊成本
            ManageBillDo billDo = manageBillDao.selectOne(new LambdaQueryWrapper<ManageBillDo>()
                    .eq(ManageBillDo::getHeaderId, headerContainerDo.getId())
                    .eq(ManageBillDo::getType, "beginBillCost"));
            if (billDo == null) {
                return 0d;
            }
            //计算该柜子下 总体积
            List<Long> orderIds = headerContainerOrderDao.selectList(new LambdaQueryWrapper<HeaderContainerOrderDo>()
                    .eq(HeaderContainerOrderDo::getHeaderContainerId, headerContainerDo.getId())).stream().map(HeaderContainerOrderDo::getFirstVesselOrderId).collect(Collectors.toList());
            //汇率
            ManageHeaderRateDo headerRateDo = manageHeaderRateDao.selectOne(new LambdaQueryWrapper<ManageHeaderRateDo>()
                    .eq(ManageHeaderRateDo::getHeaderId, headerContainerDo.getId()).eq(ManageHeaderRateDo::getType, "header"));
            if (headerRateDo == null) {
                log.error("订单id:" + orderId + "未匹配到汇率");
                return 0d;
            }
            float totalVol = 0f;
            //计算账单下商品总体积
            for (Long id : orderIds) {
                totalVol = MathUtils.add(totalVol, this.getTotalVolByOrderId(id));
            }
            if (totalVol == 0f) {
                return 0d;
            }

            //成本的 项目金额
            List<ManageHeaderPriceItemDo> headerPriceItemDoList = manageHeaderPriceItemDao.selectList(new LambdaQueryWrapper<ManageHeaderPriceItemDo>()
                    .eq(ManageHeaderPriceItemDo::getBillId, billDo.getId())); //beginBillCost beginBillCostJp

            return this.getUnitCostByPriceItem(headerPriceItemDoList, headerRateDo, vol, totalVol);
        }
    }

    /**
     * 把项目金额转成 美金,并 按体积 均摊费用
     * @param headerPriceItemDoList
     * @param headerRateDo
     * @return
     */
    public double getUnitCostByPriceItem(List<ManageHeaderPriceItemDo> headerPriceItemDoList, ManageHeaderRateDo headerRateDo, float vol, float totalVol) {
        //转换成美金
        double cost = 0;
        for (ManageHeaderPriceItemDo headerPriceItemDo : headerPriceItemDoList) {
            if (DicBusinessItemConstant.CurrencyTypeRmb.equals(headerPriceItemDo.getCurrencyType())) {
                //RMB
                cost = MathUtils.add(cost, MathUtils.div(headerPriceItemDo.getPrice() + headerPriceItemDo.getTax(), headerRateDo.getUsdRate()));
            } else if ((DicBusinessItemConstant.CurrencyTypeJpy).equals(headerPriceItemDo.getCurrencyType())) {
                //JPY
                cost = MathUtils.add(cost, MathUtils.div(MathUtils.mul(headerPriceItemDo.getPrice() + headerPriceItemDo.getTax(), headerRateDo.getJpyRate()), headerRateDo.getUsdRate()));
            } else {
                //美金
                cost = MathUtils.add(cost, headerPriceItemDo.getPrice() + headerPriceItemDo.getTax());
            }
        }
        //按体积 均摊这个订单的费用
        cost = MathUtils.mul(cost, MathUtils.div(vol, totalVol));
        return MathUtils.div(20, cost, MathUtils.numberFormat(vol + ""));
    }


    /**
     * 计算一个 订单下的总体积
     *
     * @param orderId
     * @return
     */
    public float getTotalVolByOrderId(Long orderId) {
        OrderInputDo et = dao.selectById(orderId);
        if (et == null) {
            return 0f;
        }
        List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(new LambdaQueryWrapper<OrderInputProductDo>().eq(OrderInputProductDo::getOrderInputId, orderId));
        Map<Long, List<OrderInputProductDo>> listMap = productDoList.stream().collect(Collectors.groupingBy(OrderInputProductDo::getProductId));
        Set<Long> productIdList = listMap.keySet();
        float vol = 0f;//总体积
        for (Long productId : productIdList) {
            List<OrderInputProductDo> list = listMap.get(productId);

            ProductInfoDo productInfoDo = productInfoDao.selectById(productId);
            if (productInfoDo == null) {
                continue;
            }
            float singleVol = productInfoDo.getHeight() * productInfoDo.getWidth() * productInfoDo.getLength();
            //如果订单已上架 则按照 上架的数量计算
            int count = 0;
            if (DicBusinessItemConstant.putaway.equals(et.getStatus()) || DicBusinessItemConstant.inPutTurnFba.equals(et.getStatus())) {
                count = list.stream().mapToInt(OrderInputProductDo::getReceiveCount).sum() + list.stream().mapToInt(OrderInputProductDo::getBrokenCount).sum();
            } else {
                count = list.stream().mapToInt(OrderInputProductDo::getCount).sum();

            }
            vol = MathUtils.calcFloatValue(vol, MathUtils.calcFloatValue(singleVol, count, "multiply"), "add");
        }
        return vol;
    }


}
